Why Do You Need PHP FastCGI Process Manager?

php fpm blog Plesk

PHP-FPM (an acronym of FastCGI Process Manager) is a hugely-popular alternative PHP (Hypertext Processor) FastCGI implementation.

As you may or may not know, PHP is one of the biggest open-source software programming languages utilized online. It features heavily in web development across such well-known platforms as Drupal, Magento, and WordPress, and was originally devised to preprocess plain text in UTF-8.

When PHP was invented by Rasmus Lerdorf in the mid-’90s, it was one of the first languages capable of featuring within HTML coding with no need to call external files.

Lerdorf’s scripting language has continued to evolve over the decades since, and it’s now supported by any web platform or operating system. However, as PHP’s publication is under the PHP licence, it’s incompatible with GNU General Public License because of restrictions related to the PHP term.

PHP-FPM Key Features

PHP-FPM includes numerous features that can prove beneficial for websites receiving traffic in large volumes frequently. These are:

  • Ability to start workers using various uid/gid/chroot/environment and php.ini, which replaces the safe mode users may expect
  • In-depth management for simple stop/start processing
  • Logging of stdout and stderr
  • Emergency restart available, in the event of an opcode cache being destroyed accidentally
  • Support for uploads is faster
  • Based on php.ini configuration files
  • Slowlog variable configuration for detecting functions that take longer than usual to execute
  • FastCGI improvements, with a special function for stopping and downloading data while completing long processes (e.g. processing statistics)
  • Basic stats are available, similar to the mod-status module in Apache

PHP-FPM and Nginx

Nginx is the ideal combination with PHP-FPM. Why? Because it’s a stable web server recognized for its impressive performance and low resource-consumption.

It features an asynchronous structure that’s highly-scalable, according to events. On top of this, memory consumption performance is significantly better when using Nginx and PHP-FPM together.

PHP runs as an isolated service when you use PHP-FPM. Employing this PHP version as the language interpreter means requests will be processed via a TCP/IP socket, and the Nginx server handles HTTP requests only, while PHP-FPM interprets the PHP code. Taking advantage of two separate services is vital to become more efficient.

PHP-FPM and HHVM

Nobody uses HHVM (HipHop Virtual Machine) anymore, as it’s unavailable. This was an open-source virtual machine, based on the Just-in-Time (JIT) compiler, serving as a PHP and Hack execution engine.

HHVM executes PHP or Hack code in intermediate Bytecode HipHop code, through the use of the Just-in-Time compiler principle. This code is converted into machine code at a later point, before being optimized natively and, eventually, executed.

This is a stark contrast to the standard PHP interpreted execution: the Zend Engine converts PHP code into opcode, via the Zend Engine virtual CPU.

PHP’s last version, along with FPM, means the language’s performance is now the same — or even better — without needing to use HHVM. It’s compatible with the majority of PHP 7 functions.

Before PHP 7 arrived, the PHP HHVM processor (created by Facebook, available on GitHub with Zend and PHP licenses) was typically used.

PHP-FPM and WordPress

An Nginx server with PHP-FPM support is crucial if you operate an online newspaper, content platform, or WordPress site receiving a huge number of visits daily. This set up enables you to facilitate the execution of your WordPress CMS’s PHP code to a higher standard.

PHP-FPM and Magento

Magento, a popular ecommerce platform, integrates with Nginx and PHP-FPM well. If you want to achieve your online store’s top performance, you’ll need to use this web server along with PHP-FPM support. Balancer and caches are essential, too.

PHP-FPM is a very challenging topic for newcomers, but we hope this guide has shed light on it. You should feel more comfortable with PHP-FPM, its features, and everything else covered above now that you’ve read our expert insights!

PHP-FPM and Plesk

To insure high performance and low memory consumption for highly loaded web apps PHP-FPM handler is available under Plesk. You need to make sure that PHP-FPM is installed and the option “Process PHP by nginx” is on under Websites & Domains > YourDomain > Web Server Settings.

Conclusion

PHP-FPM is an efficient method on how to minimize the memory consumption and rise the performance for the websites with heavy traffic. It is significantly faster than traditional CGI-based methods in multi-user PHP environments. If your primary goal for hosting your web application is to achieve optimal performance and security, then PHP-FPM is the way forward.

NGINX vs Apache – Which Is the Best Web Server in 2020?

NGINX vs Apache – which server is superior? NGINX and Apache are two of the biggest open source web services worldwide, handling more than half of the internet’s total traffic. They’re both designed to handle different workloads and to complement various types of software, creating a comprehensive web stack.

But which is best for you? They may be similar in many ways, but they’re not identical. Each has its own advantages and disadvantages, so it’s crucial that you know when one is a better solution for your goals than the other.

In this in-depth guide, we explore how these servers compare in multiple crucial ways, from connection handling architecture to modules and beyond.

First, though, let’s look at the basics of both Nginx and Apache before we take a deeper dive.

NGINX - NGINX vs Apache - Plesk

NGINX Outline

NGINX came about because of a grueling test, where a server has to reach 10,000 client connections all at the same time. It uses a non-synchronized, event-driven architecture to cope with this prodigious load. And its design means that it can take high loads and loads that vary wildly all in its stride, leveraging predictions for RAM usage, CPU usage, and latency to achieve greater efficiently.

NGINX is the brainchild of Igor Sysoev in 2002. He saw it as a solution to the C10K issue causing issues for web servers handling thousands of connections at the same time. He released it initially in 2004, and this early iteration achieved its objective through the utilization of an events-driven, asynchronous architecture.

Since its public release, NGINX has continued to be a popular choice, thanks to its lightweight utilization of resources and its flexibility to scale simply even with minimal equipment. As fans will testify, NGINX is excellent at serving static content with speed and efficiency, due to its design to pass dynamic requests to different software, which suits the specific purposes more effectively.

Administrators tend to choose NGINX because of such resource efficiency and responsiveness.

Apache - NGINX vs Apache - Plesk

Apache Outline

Robert McCool is credited with producing the Apache HTTP Server back in 1995. But as of 1999, it has been managed and maintained by the Apache Software Foundation instead. Apache HTTP Server is generally known as “Apache”, due to the HTTP web server being the foundation’s initial — and most popular — project.

Since 1996, Apache has been recognized as the internet’s most popular server, which has led to Apache receiving considerable integrated support and documentation from subsequent software projects. Administrators usually select Apache because of its power, wide-ranging support, and considerable flexibility.

It can be extended with its dynamically loadable module system, and is capable of processing various interpreted languages with no need to connect to external software

Apache vs NGINX – Handling Connections

One of the most significant contrasts between Nginx and Apache is their respective connection- and traffic-handling capabilities.

As NGINX was released following Apache, the team behind it had greater awareness of concurrency issues plaguing sites at scale. The NGINX team was able to use this knowledge to build NGINX from scratch to utilize a non-blocking, asynchronous, event-driven algorithm for handling connections. NGINX is designed to spawn worker processes capable of handling many connections, even thousands, courtesy of a fast-looping function. This searches for events and processes them continuously. As actual work is decoupled from connections easily, every worker is free to make connections only after new events are activated.

Every connection handled by the workers is situated in the event loop, alongside numerous others. Events inside the loop undergo asynchronous processing, so that work is handled in a non-blocking way. And whenever each connection closes, it will be taken out of the loop. NGINX can scale extremely far even with limited resources, thanks to this form of connection processing. As the single-threaded server doesn’t spawn processes to handle every new connection, CPU and memory utilization remains fairly consistent during periods of heavy load.

Apache offers a number of multi-processing modules. These are also known as MPMs, and are responsible for determining how to handle client requests. This enables administrators to switch its connection handling architecture simply, quickly, and conveniently.

So, what are these modules?

mpm-prefork

This Apache module creates processes with one thread to handle each request, and every child is able to accommodate one connection at one time. Provided the volume of requests remains less than that of processes, this module is capable of extremely fast performance.

But it can demonstrate a serious drop in quality when the number of requests passes the number of processes, which means this module isn’t always the right option.

Every process with this module has a major effect on the consumption of RAM, too, which makes it hard to achieve effective scaling. However, it could still be a solid choice when utilized alongside additional components built without consideration of threads. E.g. as PHP lacks thread safety, this module could be the best way to work with mod_php (Apache’s module for processing these specific files) safely.

mpm_worker

Apache’s mpm_worker module is designed to spawn processes capable of managing numerous threads each, with each of those handling one connection. Threads prove more efficient than processes, so this MPM offers stronger scaling than the module discussed above.

As there are no more threads than processes, fresh connections can take up one of the free threads rather than waiting for another suitable process to come along.

mpm_event

Apache’s third module can be considered similar to the aforementioned mpm_worker module in the majority of situations, though it’s been optimised to accommodate keep-alive connections. This means that, when using the worker module, connections continue to hold threads, whether or not requests are made actively for the full period during which the connection remains alive.

It’s clear that Apache’s connection handling architecture offers considerable flexibility when selecting various connections and request-handling algorithms. Options provided are primarily a result of the server’s continued advancement, as well as the growing demand for concurrency as the internet has changed so dramatically.

Apache vs NGINX – Handling Static and Dynamic Content

When pitting Nginx vs Apache, their ability to handle static and dynamic content requests is a common point of comparison. Let’s take a closer look.

NGINX is not designed for native processing of dynamic content: it has to pass to an external processor to handle PHP and other dynamic content requests. It will wait for content to be returned when it has been rendered, before relaying the results back to the client.

Communication has to be set up between NGINX and a processor across a protocol which NGINX can accommodate (e.g. FastCGI, HTTP, etc.). This can make things a little more complicated than administrators may prefer, particularly when attempting to anticipate the volume of connections to be allowed — an extra connection will be necessary for every call to the relevant processor.

Still, there are some benefits to using this method. As the dynamic interpreter isn’t integrated within the worker process, the overhead applies to just dynamic content. On the other hand, static content may be served in a simpler process, during which the interpreter is only contacted when considered necessary.

Apache servers’ traditional file-based methods mean they’re capable of handling static content, and their performance is primarily a function of those MPM methods covered earlier.

But Apache is designed to process dynamic content too, by integrating a processor of suitable languages into every worker instance. As a result, Apache can accommodate dynamic content in the server itself, with no need to depend on any external components. These can be activated courtesy of the dynamically-loadable modules.

Apache’s internal handling of dynamic content allows it to be configured more easily, and there’s no need to coordinate communication with other software. Modules may be swapped out if and when requirements for content shift.

NGINX or Apache – How Does Directory-level Configuration Work?

Another of the most prominent differences administrators discuss when discussing Apache vs NGINX relates to directory-level configuration, and whether it’s allowed in their content directories. Let’s explore what this means, starting with Apache.

With Apache, additional configuration is permitted on a per-directory level, through the inspection of files hidden within content directories — and the interpretation of their directives. They’re referred to as .htaccess.

As .htaccess files are located inside content directories, Apache checks every component on the route to files requested, applying those directives inside. Essentially, this allows the web server to be configured in a decentralized manner, typically utilized for the implementation of rewritten URLs, accessing restrictions, authentication and authorization, as well as caching policies.

Though these offer configuration in Apache’s primary configuration file, there are some key advantages to .htaccess files. First and foremost, they’re implemented instantly without needing to reload the server, as they’re interpreted whenever they’re located on a request path.

Secondly, .htaccess files enable non-privileged users to take control of specific elements of their web content without granting them complete control over the full configuration file.

This creates a simple way for certain software, such as content management systems, to configure environments without giving entry to central configuration files. It’s used by shared hosting providers for maintaining control of primary configurations, even while they offer clients their own directory control.

With NGINX, interpretation of .htaccess files is out of the question.It also lacks a way to assess per-directory configuration beyond the primary configuration file. As a result, it could be said to offer less flexibility than Apache, though it has a number of benefits too.

Specifically, improved performance is one of the main advantages compared to the .htaccess directory-level configuration system. In the case of standard Apache setups that accommodate .htaccess in any one directory, the server assesses the files in every parent directory leading to the file requested, whenever a request is made. Any .htaccess files found throughout this search will be read before being interpreted.

So, NGINX can serve requests in less time, due to its single-directory searches and file-reads for every request. Of course, this is based on files being located in a directory with a conventional structure.

Another benefit NGINX offers with directory-level configuration relates to security. Distributing access also leads to a distribution of security responsibility to single users, and they might not all be trustworthy. When administrators retain control of the whole server, there’s less risk of security-related problems which grant access to people who can’t be relied upon.

How does File and URI-based Interpretation Work with NGINX and Apache?

When discussing Nginx vs Apache, it’s important to remember the way in which the web server interprets requests, and maps them to system resources, is another vital issue.

When NGINX was built, it was designed to function as a web and proxy server. The architecture demanded to fulfil both roles means NGINX works with URIs mainly, and translates to the filesystem as required. This is evident in a number of ways in which its configuration files function.

NGINX has no means of determining filesystem directory configuration. As a result, it’s designed to parse the URI. NGINX’s main configuration blocks are location and server blocks: the former matches parts of the URI which come after the host and port, while the latter interprets hosts requested. Requests are interpreted as a URI, rather than one of the filesystem’s locations.

In the case of static files, requests are eventually mapped to a filesystem location. NGINX chooses the location and server blocks for handling the specific request, before combining the document root with the URI. It also adapts whatever’s required, based on the configuration specified.

With NGINX designed to parse requests as URIs rather than filesystem positions, it makes for simpler functionality in various areas. Specifically, in the following server roles: web, proxy, and mail. This means NGINX is easily configured by laying out appropriate responses to varied request patterns, and NGINX only checks filesystems when it’s prepared to serve the request. This is why it doesn’t implement .htaccess files.

Interpret requests as physical resources on a filesystem. It may also interpret requests as a URI location, which demands an assessment that’s a little less specific. Generally, Apache utilizes <Directory> or <Files> blocks for these purposes, and <Location> blocks for resources that are more abstract.

As Apache was conceived as a server for the web, its standard function is interpreting requests as traditional filesystem resources. This process starts with the document root and changing the part of the request which comes after host and port numbers, as it attempts to locate an actual file. So, on the web, filesystem’s hierarchy appears in the form of the available document tree.

Apache gives various alternatives for when requests fail to match underlying filesystems. E.g., Alias directives may be utilized for mapping alternative placements. Leveraging <Location> blocks is a way to work with the URI rather than the filesystem. A number of expression variants may be utilized to apply configuration throughout filesystems with greater flexibility.

As Apache is capable of functioning on the webspace and underlying filesystems, it has a heavier focus on filesystem methods. This is evident in a number of the design choices, such as the presence of .htaccess files in per-directory configuration. Apache documentation advises not to utilize URI-based blocks for inhibiting access when requests match those underlying filesystems.

NGINX vs Apache: How Do Modules Work?

When considering Apache vs NGINX, bear in mind that they can be extended with module systems, though they work in significantly different ways.

NGINX modules have to be chosen and compiled into its core software, as they cannot be dynamically loaded. Some NGINX users it’s less flexible as a result. This may be particularly true for those who feel unhappy managing their compiled software that’s positioned external to the distribution’s conventional packaging system.

Even though packages typically include modules which are used commonly, you would need to create the server from source if you need a non-standard module. Still, NGINX is incredibly useful, allowing users to dictate what they want out of their server by including only the functionality you plan to utilize.

For many people, NGINX seems to offer greater security as a result of this. Arbitrary components are unable to connect to the server. But if the server is in a scenario where this appears to be likely, it may have been affected already.

Furthermore, NGINX modules offer rate limiting, geolocation, proxying support, rewriting, encryption, mail functionality, compression, and more.

With Apache, the module system provides users with the option to load or unload modules dynamically based on your individual needs. Modules may be switched on and off even though the Apache core remains present at all times, so you can add or take extra functionality away and hook into the main server.

With Apache, this functionality is utilized for a wide range of tasks, and as this platform is so mature, users can choose from a large assortment of modules. Each of these may adjust the server’s core functionality in various ways, e.g. mod_php embeds a PHP interpreter into all of the running workers.

However, modules aren’t restricted to processing dynamic content: some of their functions include authenticating clients, URL rewriting, caching, proxying, encrypting, compression, and more. With dynamic modules, users can expand core functionality significantly — with no need for extensive extra work

NGINX or Apache: How do Support, Documentation, and Other Key Elements Work?

When trying to decide between Apache or Nginx, another important factor to bear in mind is actually getting set-up and the level of support with other software.

The level of support for NGINX is growing, as a greater number of users continue to implement it. However, it still has some way to go to catch up with Apache in certain areas.

Once upon a time, it was hard to gather detailed documentation for NGINX (in English), as the majority of its early documentation was in Russian. However, documentation has expanded since interest in NGINX has grown, so there’s a wealth of administration resources on the official NGINX website and third parties.

On the topic of third-party applications, documentation and support is easier to find. Package maintainers are starting to offer choices between NGINX and Apache auto-configuring. It’s easy to configure NGINX to complement alternative software without any support, as long as the specific project documents clear requirements (such as headers, permissions, etc.).

Support for Apache is fairly easy to find, as it’s been such a popular server for such a long time. An extensive library of first- and third-party documentation is on offer out there, for the core server and task-based situations that require Apache to be hooked up with additional software.

As well as documentation, numerous online projects and tools involve tools to be bootstrapped within an Apache setting. This could be present in the projects or the packages managed by the team responsible for the distribution’s packaging.

Apache receives decent support from external projects mainly due to the market share and the sheer number of years it’s been operating. There may be a higher likelihood of administrators having experience of using Apache, not just because it’s so prevalent but as a lot of them begin in shared-hosting scenarios which rely on Apache, due to the .htaccess distributed management capabilities.

NGINX vs Apache: Working with Both

Now that we’ve explored the advantages and disadvantages of NGINX and Apache, you could be in a better position to understand whether Apache or NGINX is best for you. But a lot of users discover they can leverage both server’s benefits by utilizing them together.

Traditional configuration for using NGINX and Apache in unison is to position NGINX ahead of Apache. This way, it serves as a reverse proxy — enabling it to accommodate every client request. Why is this important? Because it takes advantage of the quick processing speeds and NGINX’s capabilities to handle a lot of connections at the same time.

In the case of static content, NGINX is a fantastic server, as files are served to the client directly and quickly. With dynamic content, NGINX proxies requests to Apache to be processed. Apache will then bring rendered pages back. After this, NGINX is able to send content back to clients.

Plenty of people find this is the ideal setup, as it enables NGINX to perform as a sorting machine, handling all requests and passing on those which have no native capability to serve. If you reduce Apache’s level of requests, it’s possible to reduce the level of blocking which follows when Apache threads or processes are occupied.

With this configuration, users can scale out through the addition of extra backend servers as required. NGINX may be configured to pass to a number of servers with ease, boosting the configuration’s performance and its resistance to failure.

Apache vs NGINX – Final Thoughts

It’s fair to say that NGINX and Apache offer quality performance — they’re flexible, they’re capable, and they’re powerful. Choosing which server works best for your needs depends largely on assessing your individual requirements and testing with those patterns you believe you’re likely to see.

A number of differences between these projects have a tangible effect on capabilities, performance, and the time required to implement each solution effectively. But these tend to be the result of numerous trade-offs that shouldn’t be dismissed easily. When all is said and done, there’s no web server that meets everyone’s needs every single time, so it’s best to utilize the solution that suits your objectives best.

Your Complete .htaccess Guide: Including .htaccess Basics and More

Comprehensive .htaccess Guide / .htaccess tutorial - Plesk .htaccess basics - Guides

Bookmark this .htaccess guide for any .htaccess tutorial you may need. We cover all the .htaccess basics and more for your convenience. htaccess configures the way that a server deals with a variety of requests. Quite a few servers support it, like Apache – which most commercial hosting providers tend to favor. htaccess files work at directory level, which lets them supersede universal configuration settings of .htaccess commands further up the directory tree.

Why is it called .htaccess? This type of file was initially used to limit user access to specific directories, and the name has just stuck. It uses a subset of Apache’s http.conf settings directives that give a sysadmin control over who has access to each directory.

It looks to an associated .htpasswd file for the usernames and passwords of those people who have permission to access them. .htaccess still performs this valuable function, but it’s a file that’s grown in versatility to do more besides that. So we’ll have the .htaccess basics and more explained in this article.

Where is the .htaccess file - plesk .htaccess guide

Where will I find the .htaccess file?

An .htaccess tutorial will tell you that you could find one in every folder (directory) on your server. But typically, the web root folder (the one that contains everything of your website) will have one. It will usually have a name like public_html or www. If you’ve got a directory with numerous website subdirectories, you’ll typically find an .htaccess file in the main root ( public_html ) directory. And one in all of the subdirectories (/sitename) too.

Why can’t I find the .htaccess file?

Most file systems – file names that start with a dot ( . ) will be hidden. So by default, you won’t be able to see them. However, you can still get to them. If you look at your FTP client or File Manager, you’ll likely find a setting to “show hidden files.” It may be in some other location depending on which program you use. But you’ll usually find it if you look under “Preferences”, “Settings”, “Folder Options” or “View.”

What if I don’t have an .htaccess file?

The first thing to establish is that you definitely don’t have one. Check that you have set the system to “show hidden files” (or whatever it’s called on your system). So that you can be sure it really isn’t there. You should have a .htaccess file as they’re frequently created by default, but it’s always worth checking.

If you’ve looked everywhere and you still can’t find one, never fear because .htaccess basics are not hard to understand. And we’ve got a .htaccess guide for you here. You can make one by opening a text editor and creating a new document. It should not have the .txt or any other file extension. Just .htaccess, and make sure it’s saved in ASCII format (it shouldn’t be in UTF-8 or anything) as .htaccess. Transfer it to the right directory using FTP or the file manager in your web browser.

Handling an .htaccess error code - Plesk

Handling an error code

One of your simple .htaccess basics is setting up error documents. Any .htaccess guide like this one will tell you that when a server receives a request, it responds by offering a document. Just like with HTML pages. Otherwise, it can pull that response from a particular application (as with Content Management Systems and other web apps).

If this process trips up, then the server reports an error and its corresponding code. Different types of errors have different error codes. And you’ve probably seen a 404 “Not Found” error quite a few times. It’s not the only one though.

Client Request Errors

  • 400 — Bad Request
  • 401 — Authorization Required
  • 402 — Payment Required (not used yet)
  • 403 — Forbidden
  • 404 — Not Found
  • 405 — Method Not Allowed
  • 406 — Not Acceptable (encoding)
  • 407 — Proxy Authentication Required
  • 408 — Request Timed Out
  • 409 — Conflicting Request
  • 410 — Gone
  • 411 — Content Length Required
  • 412 — Precondition Failed
  • 413 — Request Entity Too Long
  • 414 — Request URI Too Long
  • 415 — Unsupported Media Type.

Server Errors

  • 500 — Internal Server Error
  • 501 — Not Implemented
  • 502 — Bad Gateway
  • 503 — Service Unavailable
  • 504 — Gateway Timeout
  • 505 — HTTP Version Not Supported

What Happens by Default?

When there’s no specification on how to approach error-handling, the server just sends the message to the browser. Which in turn gives the user a general error message, but this isn’t especially helpful.

Creating Error Documents

At this point in your .htaccess guide, you’ll need an HTML document for each error code. You can call them anything, but you may want to consider a name that’s appropriate. Such as not-found.html or just 404.html.

Then, in the .htaccess file, determine which document goes with which error type.

ErrorDocument 400 /errors/bad-request.html

ErrorDocument 401 /errors/auth-reqd.html

ErrorDocument 403 /errors/forbid.html

ErrorDocument 404 /errors/not-found.html

ErrorDocument 500 /errors/server-err.html

Just note that each one gets its own line – and you’re done.

Alternatives to .htaccess – .htaccess guide for error-handling

Most CMS, like WordPress and Drupal – and web apps, will deal with these errors codes in their own way.

Password protection with .htaccess - Plesk

Password Protection With .htaccess

As we’ve said, .htaccess files were originally used to limit which users could get into certain directories. So let’s take a look at that in our .htaccess tutorial first.

.htpasswd –  this file holds usernames and passwords for the .htaccess system

Each one sits on its own line like this:

username:encryptedpassword

for example:

jamesbrown:523xT67mD1

Note that this password isn’t the actual one, it’s just a cryptographic hash of the password. This means that it’s been put through an encryption algorithm, and this is what came out. It works in the other direction too. So each time a user logs in, the password text goes through that same algorithm. If it matches with what the user typed, they get access.

This is a highly secure way of storing passwords. Because even if someone gets into your .htpasswd file, all they’re seeing is hashed passwords – not the real ones. And there’s no way to use them to reconstruct the password either, because the algorithm is a one-way-street.

You can choose from a few different hashing algorithms:

  • bcrypt — The securest one but chugging through the encryption process slows it down as a result. Apache and NGINX are compatible.
  • md5 — The latest versions of Apache use this as their default hashing algorithm, but NGINX doesn’t support it.

Insecure Algorithms — These are best avoided.

  • crypt() — was previously the default hashing function, but isn’t a secure option.
  • SHA and Salted SHA.

.htaccess Guide to Adding Usernames and Passwords with CLI

You can use the command line or an SSH terminal to create an .htpasswd file and add username-password pairs to it directly.

.htpasswd is the command for dealing with the .htpasswd file.

Simply use the command with the -c option to create a new .htpasswd file. Then enter the directory path (the actual path on the server, not the URL). You can also add a user if you want to.

> htpasswd -c /usr/local/blah/.htpasswd jamesbrown

This makes a new .htpasswd file in the /blah/ directory, along with a record for a user called jamesbrown. It will then ask you for a password – also encrypted and stored using md5 encryption.

If an .htpasswd file already exists at that location, the new user just becomes part of the existing file. So it won’t create a new one. Otherwise, if you’d rather use the bcrypt hashing algorithm, go with the -b option.

Password hashing without the command line

If you’re only familiar with .htaccess basics, you may choose not to use the command line or SSH terminal. In that case, you can just create an .htpasswd file. Then, just use a text editor to fill everything in before uploading using FTP or file manager.

Of course, that leaves you with the task of encrypting the passwords. But that shouldn’t be a problem because there are lots of password encryption programs online. Many other .htaccess tutorials will probably approve of the htpasswd generator at Aspirine.org. Because it offers a few choices of algorithms that let you determine how strong the password is. Once you run it, copy your hashed password into the .htpasswd file.

You’ll only need one.htpasswd file for all your.htaccess files. So there’s no need to have one for each. One will do the job for the whole main server directory or web hosting account. But don’t put your .htpasswd file in a directory that anyone can access. So, not in public_html or www or any subdirectory. It’s safer from a security standpoint to put it somewhere that is only accessible from within the server itself.

Quick .htaccess Tutorial: How to use .htpasswd with .htaccess

If you want to have a .htaccess file for every directory, you can assign a set of users to have access to it. To grant universal access, do nothing, because this is enabled by default. If you want to limit who can get access, then your .htaccess file should look like this:

AuthUserFile /usr/local/etc/.htpasswd

AuthName "Name of Secure Area"

AuthType Basic

<Limit GET POST>

require valid-user

</Limit>

Line one shows the location of where your usernames and passwords are. Line two defines the name for the area you want to keep secure, and you can call it anything. Line three specifies “Basic” authentication, which is fine in most instances.

The <Limit> tag defines what is being limited. In this instance, the ability to GET or POST to any file in the directory. Within the pair of <Limit> tags is a list of who is allowed to access files.

In this example, access files can be accessed by any valid user. If you only want certain users to have access you can name them.

AuthUserFile /usr/local/etc/.htpasswd

AuthName "Name of Secure Area"

AuthType Basic

<Limit GET POST>

require user janebrown

require user jamesbrown

</Limit>

You can also grant/deny access based on the group where you put users – which is a real-time saver. You can do this by creating a group file and adding names. Give your group file a name, such as .htpeople, and have it look something like this:

admin: janebrown jamesbrown

staff: zappafrank agrenmorgen

Now it’s become something that you can refer to in your .htaccess file:

AuthUserFile /usr/local/etc/.htpasswd

AuthGroupFile /usr/local/etc/.htpeople

AuthName "Admin Area"

AuthType Basic

<Limit GET POST>

require group admin

</Limit>

The .htaccess guide for .htpasswd alternatives

It only makes sense to use .htaccess/.htpasswd to limit server file access if you have lots of static files. This approach appeared in the early days of websites, where they consisted of lots of HTML docs and other resources. If you’re using WordPress, you’ll have a feature that lets you do this as part of the system.

Enabling Server Side Includes (SSI) – .htaccess Tutorial

SSI is a simple scripting language which you would mainly use to embed HTML documents into other HTML documents. So you can easily re-use frequently-used elements like menus and headers.

<!-- include virtual="header.shtml" -->

It’s also got conditional directives (if, else, etc.) and variables, which makes it a complete scripting language. Although one that’s hard to use if you have anything more complicated in your project than one or two includes. If it gets to that point then a developer will usually be reaching for PHP or Perl instead.

Server Side Includes are enabled by default with some web-hosting servers. If yours isn’t, you can use your .htaccess file to enable it, like this:

AddType text/html .shtml

AddHandler server-parsed .shtml

Options Indexes FollowSymLinks Includes

This should enable SSI for all files that have the .shtml extension. You can tell SSI to parse .html files using a directive like this:

AddHandler server-parsed .html

Why bother?

Well, this way lets you use SSI without alerting anyone to the fact that you are doing so. On top of that, if you change implementations later, you can hold on to your .html file extensions. The only fly in the ointment here is that every .html file will then be parsed with SSI. And if you have many .html files that don’t need SSI parsing, it makes the server work needlessly harder. Thus, bogging it down for no extra benefit.

SSI on your Index page

To avoid parsing every single.html file without using SSI on your index home, you have to stipulate in your .htaccess file. Because when the web server looks for the directory index page, it will be hunting for index.html by default. If you aren’t parsing .html files, you must name your index page “named index.shtml” if you want SSI to work. Because then, your server won’t automatically look for it. To make that happen just add:

DirectoryIndex index.shtml index.html

This lets the web server know that the index.shtml file is the main one for the directory. The second parameter, index.html is a failsafe. This gets referred when it can’t find index.shtml.

IP blacklisting - IP whitelisting - .htaccess - Plesk

IP Blacklisting and IP Whitelisting with .htaccess

If you’ve had problems from certain users/IP addresses, there are .htaccess basics you can use to blacklist/block. Otherwise, you can do the opposite and whitelist/approve everyone from particular addresses if you want to exclude everybody else.

Blacklisting by IP

This will let you blacklist addresses (numbers are examples):

order allow,deny

deny from 444.33.55.6

deny from 735.34.6.

allow from all

The first line says to evaluate the allow directives before the deny directives. This makes allow from all the default state. In this case, only those which match the deny directives will be denied. If you switched it round to say deny,allow, then the last thing it looked at would be the allow from all directive. This allows everybody, and overrides the deny statements.

Take note of the third line, which says deny from 735.34.6. This isn’t a complete IP address, but that’s okay because it denies every IP address in that block. Ergo, anything that begins with 735.34.6. You can include as many IP addresses as you like, one on each line, with a deny from directive.

Whitelisting by IP

The opposite of blacklisting is whitelisting — restricting everyone except those you specify. As you might suspect, the order directive has to be turned back to front. So that you deny access to everyone at first, but then allow certain addresses after.

order deny,allow

deny from all

allow from 111.22.3.4

allow from 789.56.4.

Domain names instead of IP addresses

You can also block or allow users of a domain name. This is helpful if people are moving between IP addresses. But it won’t work against anyone who has control of their reverse-DNS IP address mapping.

order allow,deny

deny from forinstance.com

allow from all

This works for subdomains too. In the example above, you will also block visitors from abc forinstance.com.

Block Users by Referrer – .htaccess Guide

If a website contains a link to your site and someone follows it, we call it a ‘referrer’. But this doesn’t only work for clickable hyperlinks to your website. Any page on the internet can link to your images directly. This is called hotlinking. It often steals your bandwidth, it can infringe on your copyright – and you don’t even get extra traffic from it. And it’s not just images either. A stranger can link to your other resources like CSS files and JS scripts, too.

This is bound to happen a little bit and most site owners tolerate it. But it’s the kind of thing that can easily escalate into something more abusive. And there are times when in-text clickable hyperlinks can cause you problems too. Like when they’re from troublesome or nefarious websites. These are just a few of the reasons why you may decide to deny requests that originate with particular referrers.

If you need to do this, you’ll have to activate the mod_rewrite module. Most web hosts enable it automatically. But if yours doesn’t, or you can’t tell if they have, you should get in touch and ask. If they’re reluctant to enable it – maybe think about getting a new host.

.htaccess basics – Directives that block a referrer depend on the mod_rewrite engine.

The code to block by referrer looks like this:

RewriteEngine on

RewriteCond % ^http://.*forinstance.com [NC,OR]

RewriteCond % ^http://.* forinstance2.com [NC,OR]

RewriteCond % ^http://.* forinstance3.com [NC]

RewriteRule .* - [F]

It’s slightly fiddly, so let’s go through it.

RewriteEngine on, on the first line tells the parser that some rewrite directives are on the way. Each of lines 2,3 and 4 blocks a single referring domain. To change this for your own purposes you would alter the domain name part (forinstance) and extension (.com). T

he back-slash in front of the .com is an escape character. The pattern matching used in the domain name is a standard expression. And the dot has a meaning in RegEx. So it must be “escaped” by using “/”.

The NC in the brackets is there to specify that the match shouldn’t be case sensitive. The OR literally means “or”, and indicates that more rules are on the way. As long as the URL is this one, this one or this one, go along with this rewrite rule.

The final line is the rewrite rule itself. The [F] stands for “Forbidden.” If a request comes from a referrer like the ones on the list, then it will be blocked. And a 403 Forbidden error will arrive.

Block bots and web scrapers - Plesk .htaccess Guide

An .htaccess Guide to Blocking Bots and Web Scrapers

Sometimes it isn’t even people trying to eat up your bandwidth, it’s robots. These programs come and lift your site information, typically to republish under some low-quality SEO outfit. There are genuine bots out there, such as the ones that come from the big search engines. But others are almost like cockroaches, scavenging and doing you no good whatsoever.

To date, the industry has identified hundreds of bots. You won’t ever be able to block them all, but at least, as many as possible. Here are some rewrite rules that will trip up 350+ known bots.

Specifying a Default File for a Directory

When a server receives a URL request but with no specified file name, it assumes the URL refers to a directory. So, here is a .htaccess guide on what to do. If you request http: forinstance.com, Apache (and most servers) will look for the domain in the root directory. Typically /public_html or something like it, such as /forinstance-com – in order to find the default file. The default file will be called index.html by default. Because when the Internet was young, websites were often just a bunch of docs bundled together. And “home” pages were often no more than an index, so that you knew where everything was.

Of course, nowadays you might not want index.html to be the default page. Perhaps because you may want a different file type. So index.shtml, index.xml, or index.php might be more appropriate. Or maybe you don’t think of your home page as an “index,” and want to call it something else. Like home.html or primary.html.

Set the default directory page - .htaccess

Set the Default Directory Page

One of the .htaccess basics is letting you set the default page for a directory with ease:

DirectoryIndex [filename goes here]

If you want your default to be home.html it’s as simple as using:

DirectoryIndex home.html

.htaccess Guide to Setting More Than One Default Page

You can also set more than one DirectoryIndex:

DirectoryIndex index.php index.shtml index.html

The way this works is that the web server looks for the first one first. If it can’t find that, it looks for the second one, and on it goes. But why would you need to do this? Wouldn’t you know which file you wanted to use as your default page? Keep in mind that one of the .htaccess basics is that it influences its own directory. And each subdirectory too until it’s overruled by a more local file.

So, an .htaccess file in your root directory can give instructions for lots of subdirectories. And in turn, they could all have their own default page names. So, imagine you put all those rules into just one .htaccess file in the root. Then, it spares you the tedious work of duplicating all the directives it contains at the level of every directory.

.htaccess Guide to URL Rewriting and URL Redirects

An important part of this .htaccess guide is that the most common uses of .htaccess files is URL redirects. So, for example, the URL for a document or resource may have changed. Perhaps because you’ve moved things around on your website, or you’ve changed domain names. Then, in that case, URL redirects can help you.

301 or 302

There are two types of redirect error codes that the server will generate, namely 301 and 302.

301 tells you that something has “Permanently Moved.” Meanwhile, 302 means it “Moved Temporarily.” In most cases, 301 does a perfectly good job. And perhaps more importantly, it gets SEO brownie points since the original URL may pick up from the new page.

It will also make most browsers update their bookmarks and cache the old-to-new mapping. This consequently lets them request the new URL when the original is being looked for. For a permanently changed URL these are all the responses you want.

There’s not much you can gain from using 302 redirects. Mainly, because there’s rarely a reason to change a URL on a temporary basis. Changing one at all is not something that anybody should really want to do. However, sometimes you just have to do it. And there are usually better options to changing it only to change it back later. At least, at the time of writing this .htaccess guide.

Redirect or Rewrite

You can change a URL with .htaccess directives in a couple of ways — the Redirect command and the mod_rewrite engine. The Redirect command tells the browser which other URL it should be looking out for. The mod_rewrite tool will normally “translate” the URL that’s in the request. Turns it into something the file system or CMS can understand. Then, it treats the request as though the translated URL was the one that was requested.

From the perspective of the web browser it’s business as usual. It gets the content it requested and carries on as if nothing happened.

The mod_rewrite tool is also able to produce 301 redirects that work like the Redirect command. But with a greater number of possible rules instead. Including elaborate pattern matching and rewriting instructions – which is beyond what Redirect can do.

Basic Page Redirect – .htaccess guide

For redirecting one page to another URL, the code looks like this:

Redirect 301 /relative-url.html http://forinstance.com/full-url.html

A single space separates each of the four parts of this one-line command, so you have:

  1. the Redirect command itself
  2. its type ( 301 – Moved Permanently )
  3. the original page’s relative URL
  4. the full URL of the new page.

The relative URL is relative to the directory that contains the .htaccess file. Which will normally be the web root, or the root of the domain.

So, if http://forinstance.com/blog.php had been moved to http://blog.forinstance.com, the code would be:

Redirect 301 /blog.php http://blog.forinstance.com

Redirecting a large section – .htaccess guide

Have you made changes to your directory structure yet? If you haven’t change your page names, redirect all requests for a particular directory to the new one.

Redirect 301 /old-directory http://forinstance.com/new-directory

Redirecting an entire site – .htaccess guide

But how about if your entire site has moved to a new URL? No problem.

Redirect 301 / http://thenewurl.com

Redirecting www to non-www – .htaccess guide

More and more websites are turning their back on the www subdomain. There’s never really been a need for it. It’s a throwback to when website owners used a server to look after many of their own documents. And the www directory was where they put anything they wanted to offer others.

Some still use it to this day, but many have moved on. It’s become such a habit for users to type “www.” in front of every URL. Therefore, making it tricky for you if yours has been short of those letters. However, the mod_rewrite module can help you with this. And you probably have one on your web host’s dashboard already.

Options +FollowSymlinks

RewriteEngine on

RewriteCond % ^www.forinstance.com [NC]

RewriteRule ^(.*)$ http://forinstance.org/$1 [R=301,NC]

But be careful! Many other .htaccess and mod_rewrite guides will give you some version of this code to achieve this:

Options +FollowSymlinks

RewriteEngine on

RewriteCond % !^forinstance.com [NC]

RewriteRule ^(.*)$ http://forinstcance.org/$1 [R=301,NC]

Can you see what’s wrong with it?

All subdomains are redirected to the primary domain! Which means not just www.forinstance.com, but others like blog.forinstance.com and admin.forinstance.com too. Not ideal behaviour!

Redirecting to www – .htaccess guide

So, what happens if you’re using the www subdomain? You should probably set up a redirect to make sure people get to where they’re trying to go. Especially now that fewer people are likely to automatically add that www to the beginning of URLs. All you need to do is reverse the code to achieve this.

RewriteEngine On

RewriteCond % ^forinstance.com [NC

RewriteRule ^(.*) http://www.website.com/$1 [R=301,NC]

One thing not to do:

A number of .htaccess guides recommend redirecting 404 errors to your home page. While this is possible, we’re writing here in our .htaccess guide that it’s actually an awful idea. Because it leaves visitors confused. They will be expecting another page, and instead get your homepage. A 404-error page would have told them exactly what they needed to know – whereas this does not. And anyway, what’s the problem with admitting that a page can’t be found? There’s no shame in it.

Why use the .htaccess basics in this .htaccess guide rather than other approaches? Redirects can be set up with server-side scripting, like in PHP files. They can also be set up from within your CMS – which is pretty much the same thing. But using .htaccess is usually the fastest type of redirect. With PHP-based redirects, or other server-side scripting languages, the entire request must be completed. And the script is actually interpreted before a redirect message is sent to the browser.

As any .htaccess guide will tell you, using .htaccess redirects are much faster. Mainly because the server responds to each request directly. However, be aware that some CMSs handle redirects by updating the .htaccess file in a programmatic way. Like WordPress, for example. This gives you the speed benefits of directly using .htaccess combined with the convenience of managing it from inside your application.

.htaccess Basics – Hiding Your .htaccess File

One of the .htaccess basics in this .htaccess guide is that the file shouldn’t be visible from the web. There’s just no reason for it, aside from maybe wanting to locate your .htpasswd file. And as another rule of the .htaccess guide, random strangers shouldn’t be able to look at details of your implementation. Including rewrite rules, directory settings, and security. Hiding all of that stuff makes it more difficult for hackers to work out ways into your system. Luckily, you can hide your .htaccess file fairly easily using this code:

<Files .htaccess>

order allow,deny

deny from all

</Files>

MIME types - .htaccess - Plesk

.htaccess guide to MIME types

MIME types are file types – originally for email (“Multipurpose Internet Mail Extensions”). But don’t just think of them as “file types” because MIME suggests a specific format for specifying them. If you’ve ever written an HTML doc, you’re likely to have specified a MIME type. Probably even without realising it:

<style type=”text/css” src=”/style.css” />

The type attribute refers to a particular MIME type.

MIME types on your server

Occasionally you might find that your web server isn’t set up to deliver a specific file type. And any requests for that type of file just don’t work. Usually, you can get around this by putting the MIME type in your .htaccess file.

AddType text/richtext rtx

This directive has three space-separated parts:

  1. The AddType command
  2. The MIME type
  3. The file extension.

You can associate a number of different file extensions with the same MIME type on one line.

AddType video/mpeg mpg MPEG MPG  

Force Download by MIME Type

Want every link to a type of file to automatically download, rather than just open in your browser? Then, use the MIME type application/octet-stream, like this:

AddType application/octet-stream pdf

As before, you can include numerous file extensions:

AddType application/octet-stream rtf txt pdf docx doc

List of File Extensions and MIME Types – .htaccess basics

Here’s an incomplete list of file formats and associated MIME types. If you manage your own website, you may already know your file types. Therefore, you don’t need to paste the whole list into your .htaccess file. But if you run a site with others who could be uploading all sorts of stuff, then yes. This might help to avoid any potential publishing mishaps. This particularly relates to file sharing or project management sites where folks are bound to be sharing lots of files.

AddType application/macbinhex-40 hqx

AddType application/netalive net

AddType application/netalivelink nel

AddType application/octet-stream bin exe

AddType application/oda oda

AddType application/pdf pdf

AddType application/postscript ai eps ps

AddType application/rtf rtf

AddType application/x-bcpio bcpio

AddType application/x-cpio cpio

AddType application/x-csh csh

AddType application/x-director dcr

AddType application/x-director dir

AddType application/x-director dxr

AddType application/x-dvi dvi

AddType application/x-gtar gtar

AddType application/x-hdf hdf

AddType application/x-httpd-cgi cgi

AddType application/x-latex latex

AddType application/x-mif mif

AddType application/x-netcdf nc cdf

AddType application/x-onlive sds

AddType application/x-sh sh

AddType application/x-shar shar

AddType application/x-sv4cpio sv4cpio

AddType application/x-sv4crc sv4crc

AddType application/x-tar tar

AddType application/x-tcl tcl

AddType application/x-tex tex

AddType application/x-texinfo texinfo texi

AddType application/x-troff t tr roff

AddType application/x-troff-man man

AddType application/x-troff-me me

AddType application/x-troff-ms ms

AddType application/x-ustar ustar

AddType application/x-wais-source src

AddType application/zip zip

AddType audio/basic au snd

AddType audio/x-aiff aif aiff aifc

AddType audio/x-midi mid

AddType audio/x-pn-realaudio ram

AddType audio/x-wav wav

AddType image/gif gif GIF

AddType image/ief ief

AddType image/jpeg jpeg jpg jpe JPG

AddType image/tiff tiff tif

AddType image/x-cmu-raster ras

AddType image/x-portable-anymap pnm

AddType image/x-portable-bitmap pbm

AddType image/x-portable-graymap pgm

AddType image/x-portable-pixmap ppm

AddType image/x-rgb rgb

AddType image/x-xbitmap xbm

AddType image/x-xpixmap xpm

AddType image/x-xwindowdump xwd

AddType text/html html htm

AddType text/plain txt

AddType text/richtext rtx

AddType text/tab-separated-values tsv

AddType text/x-server-parsed-html shtml sht

AddType text/x-setext etx

AddType video/mpeg mpeg mpg mpe

AddType video/quicktime qt mov

AddType video/x-msvideo avi

AddType video/x-sgi-movie movie

AddType x-world/x-vrml wrl

Block hotlinking - .htaccess - Plesk

Block Hotlinking – .htaccess Guide

Hotlinking is where you link to resources from other domains rather than hosting the files yourself. A good example would be a video that you really like on someone else’s site. You can either download it, upload it to your site (assuming no copyright, of course) and embed in your page.

<img src=”http://yourdomain.com/video.mpg”>

The hotlinking route saves you the bother and the bandwidth. And no, that doesn’t mean we condone it—quite the opposite in fact.

<img src=”http://originaldomain.com/video.mpg”>

This kind of thing also goes on with CSS and JS files – but it mostly happens with pictures and video. Sites like Wikipedia don’t really mind you doing this. And there are others who want you to do it because it helps their SEO needs. Then there are the likes of JQuery, which uses a CDN to share their JS libraries so you don’t have to host them yourself. But a lot of web hosts see hotlinking as a way of stealing their material and hogging their bandwidth.

If your site’s not really big, then you don’t want to be getting thousands of requests every day. Especially considering they don’t bring visitors to your site or benefit you in any way. So, if hotlinking is only raising your blood pressure, then you can block it. Simply by adding some mod_rewrite rules to your .htaccess file.

RewriteEngine on

RewriteCond % !^$

RewriteCond % !^http://(www.)?forinstance.com/.*$ [NC]

RewriteRule .(gif|jpg|jpeg|png|js|css)$ - [F]

Don’t forget to change forinstance.com in line 3 to your genuine domain name. This way, we catch any requests that don’t originate from your domain. And check them to see if they match one of the file extensions you’ve identified in line 4. If there’s any match – request denied. You can also easily add other file extensions to the list by editing the final line.

Enabling CGI Everywhere

CGI – Common Gateway Interface, is a server-side method that includes non-HTML scripts (like SSI or Perl) in web pages. CGI scripts are normally in a folder named /cgi-bin. The server’s configurations are to treat any resource in that directory as a script, instead of a page.

The problem is URLs which reference CGI resources must have /cgi-bin/ in them. So they can place implementation details into your URL – an inverse pattern you should steer clear of for a few reasons. Meanwhile, an elaborate site may need a better structure than just having loads of scripts crammed into one/cgi-bin folder.

For your server to parse CGI scripts, regardless of directory location, just put this in your .htaccess file:

AddHandler cgi-script .cgi

Options +ExecCGI

If you have other file extensions you’d like to process as CGI scripts, just add them to the first line.

Scripts as Source Code

Most of the time, all the scripts go in your web directory because they need to run as scripts. But maybe you want site visitors to be able to view the source code, instead of just executing it. Your .htaccess file can help you do this by stripping the script handler for particular types of file. And then putting them in a handler for text instead.

RemoveHandler cgi-script .pl .cgi .php .py

AddType text/plain .pl .cgi .php .py

Alternatively, you can specify for these file extensions to download by default, instead of just appearing on display.

RemoveHandler cgi-script .pl .cgi .php .py

AddType application/octet-stream .pl .cgi .php .py

Be on your guard with both of these, though. Because if you’re still using these scripts for the rest of your website, that directive in your web root’s .htaccess file is going to cause you headaches. You’re better off putting scripts you only want to display into their own designated directory. And then putting the directive into an .htaccess file in that same folder.

PHP settings - .htaccess - Plesk

Configuring PHP Settings

Sometimes you need to tweak PHP settings, and this is best done using a file called php.ini. The thing is, some hosting companies, particularly shared hosters, won’t let their customers do that. But you can get around this, by embedding php.ini rules in your .htaccess file. Here’s the syntax:

php_value [setting name] [value]

So, let’s say you want to increase the maximum file upload size. You’d just say:

php_value upload_max_filesize  12M

You can’t specify every PHP setting in a .htaccess file. For instance, you can’t disable_classes like this. To see a full list of all php.ini settings, check out the official php.ini directives guide.

When Not to Use .htaccess

When you first edit your .htaccess file you can suddenly feel as powerful as a sysadmin. But try not to let absolute power corrupt you. Because you may find yourself misusing the .htaccess file. When all you have is a hammer, then every task can start to look like a nail. But at least sometimes, when something seems like an .htaccess task, your directive is better off somewhere else.

Further Up the Tree

When you feel like putting a directive in an .htaccess file, you should probably choose the httpd.conf file instead. It’s a configuration settings file for the whole server. The proper home of PHP settings too is the php.ini file, and most languages have their own equivalents.

So say you put directives higher up in the tree, in the httpd.conf, php.ini, or other appropriate file for that language. Then, you can embed those settings in the server’s parsing engine. With .htaccess, you must check and interpret the directives every time there’s a request.

This isn’t so bad if you’re running a low-traffic site with just a few .htaccess directives. But it isn’t difficult to see if your site is traffic-heavy and has to churn through lots of directives. You’re effectively putting the brakes on the whole thing.

It’s a shame that a lot of shared hosting providers won’t let their customers into the httpd.conf or php.ini files. Hence, forcing them to settle for the slower .htaccess file.

This doubly penalizes them when you compare them side-by-side with custom VPS configurations. Because shared hosting is also usually under-resourced. That’s why a site with a decent level of traffic is probably better off with VPS instead of shared hosting.

.htaccess troubleshooting basics - Plesk

WordPress .htaccess File in Action: Usage Basics

WordPress and .htaccess - Plesk

Yes, WordPress reigns supreme as a CMS, so most modern developers will have encountered WordPress in their daily activities. We’re using this tutorial to explain how one of WordPress’s most important components works. See why the .htaccess file is so important to WordPress functionality, and learn more about configuring your own .htaccess file.

What exactly is a WordPress .htaccess file?

If this is totally familiar to you – great! But if you’ve never heard of the .htaccess file – there’s a reason for that. In almost all cases the .htaccess file will be hidden in your root directory. And sometimes you simply won’t have an .htaccess file at all.

Note that .htaccess is not something unique to WP at all. In fact, it relates to the Apache web server that drives countless websites – including WordPress. So .htaccess is basically a web server configuration file. Your Apache server will look for the .htaccess document whenever it starts your website. And if it exists – it will obey the instructions in it.

Essentially, the .htaccess file helps configure specific Apache settings in order for the web server meet your specific application needs. This could include toggling on or off server functions. Or for example, making a redirect where users who do not add “www” in front of a domain name gets redirected to www.yourdomain.com.

.htaccess is also a way to tighten up security because you can also set privileges for some files. Meanwhile, you can block bots and add additional file handling capabilities via MIME types. Many settings in the .htaccess file are relevant for developers who use it to customize their WordPress.

Creating a default .htaccess file for use in a WordPress instance

Creating a wordpress .htaccess file

Every new WordPress installation will come with a .htaccess file as soon as you install it on Apache. But note that the .htaccess file will be hidden so you must select “show hidden files.” Or a similar option in your operating system. Note that occasionally a WordPress site won’t have a .htaccess file – for example, because of permission-related issues.

Here we’ll explain how to create an .htaccess. The process is broadly similar for most file managers – including those coming with Plesk or cPanel. Alternatively, you can use your computer to create the file and simply upload using a file manager or FTP.

You need to navigate to the root directory of your WP instance – it’s usually simply called public_html. Here, create a new text file and call it “.htaccess”. You can then open this file in a plain text editor of your choice. You’ll notice a few lines of text which basically specifies the default settings for your WordPress site. By  default, the WordPress .htaccess file will contain the following code:

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

To make your own file, simply copy the code above and paste it into the .htaccess file you just created. Then save the file, closing your text editor. That’s it, you have just made a brand new .htaccess file. We suggest you visit your website to make sure that it is working. Because a .htaccess file which is not correctly specified will lead to errors, including the dreaded 500 internal error.

Fine-tuning your WordPress instance using the power of .htaccess

When we talk about WordPress performance – not everything depends on WordPress configuration itself. So certain aspects are directly related to web server configuration. Since .htaccess gives you some additional ways on how to control Apache on the level of the certain website . You may use it to fine-tune your WordPress site overall performance.

Browser Caching

Browser caching allows visitors to save items from your web pages. In this case they don’t need to download them again and again while visiting your website. Usually it helps to reduce bandwidth and reduce page loading time.

<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType image/jpg "access 1 year"
ExpiresByType image/jpeg "access 1 year"
ExpiresByType image/gif "access 1 year"
ExpiresByType image/png "access 1 year"
ExpiresByType text/css "access 1 year"
ExpiresByType application/pdf "access 1 month"
ExpiresByType text/x-javascript "access 1 month"
ExpiresByType application/x-shockwave-flash "access 1 month"
ExpiresByType image/x-icon "access 1 year"
ExpiresDefault "access 3 days"
</IfModule>

File Caching

Server-side file caching helps to serve multiple visitors within the same cache. As a result, the server load reduces and the speed of each page view increases.

Cache htm/html files for 1 week:


<FilesMatch ".(html|htm)$">
Header set Cache-Control "max-age=43200"
</FilesMatch>

Cache plain text files, css and js files for 1 week:


<FilesMatch ".(js|css|pdf|txt)$">
Header set Cache-Control "max-age=604800"
</FilesMatch>

Cache images for one month:


<FilesMatch ".(gif|jpg|jpeg|png)$">
Header set Cache-Control "max-age=2592000"
</FilesMatch>

 

Disable caching for dynamic files:


<FilesMatch "\.(php|pl|cgi|spl|scgi|fcgi)$">
ExpiresActive Off
</FilesMatch>

Gzip compression on Apache

By enabling gzip compression, you can reduce the size of html, js and css files up to 70%:


<IfModule mod_gzip.c>
mod_gzip_on Yes
mod_gzip_dechunk Yes
mod_gzip_item_include file \.(html?|txt|css|js|php|pl)$
mod_gzip_item_include handler ^cgi-script$
mod_gzip_item_include mime ^text/.*
mod_gzip_item_include mime ^application/x-javascript.*
mod_gzip_item_exclude mime ^image/.*
mod_gzip_item_exclude rspheader ^Content-Encoding:.*gzip.*
</IfModule>

Proper character set

In order to inform the browser about certain character set usage required to render the page, you need to specify the page’s character set.

AddDefaultCharset utf-8

Disable image hotlinking

It’s not always a good idea to allow others to use your images on their website with a direct link. Especially considering your server resources and bandwidth. The solution is simple:


RewriteEngine on
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^http(s)?://(www\.)?bing.com [NC]
RewriteCond %{HTTP_REFERER} !^http(s)?://(www\.)?google.com [NC]
RewriteRule \.(jpg|jpeg|png|gif)$ – [NC,F,L]

Disable Directory Browsing

Additionally, directory browsing may give a lot of useful information for those who plan to hack your website. To fix this you may use the following:

Options -Indexes

Important files protection

Finally, it’s possible to protect vital files including local php.ini ( if any ), wp-config.php and error logs:


<FilesMatch "^.*(error_log|wp-config\.php|php\.ini|\.[hH][tT][aApP].*)$">
Order deny,allow
Deny from all
</FilesMatch>

WordPress .htaccess usage – In conclusion

To sum up, you need your .htaccess for WordPress to work the way it should. Meanwhile, understand that your .htaccess file can also give you more control over your server features and performance. At the same time, keep an eye out for errors inside the .htaccess file since they may lead to inaccessibility of your website.

If you’re interested in getting exceptional performance for your website, solid security and simple management, try WordPress Toolkit with Plesk. Many have found this to be the optimal solution for their WordPress-based business.

Moving from HTTP to HTTPS 3: Troubleshooting and DIY solutions

Moving from HTTP to HTTPS 3: Troubleshooting and DIY solutions - Plesk

One thing is quite clear- HTTPS is here for good. When SSL certificates give you HTTPS status, you’re saving user data from hackers, making the internet a safer place. You’re also increasing online transactions on e-commerce sites. That’s why most serious website owners have already migrated from HTTP to HTTPS – or are attempting it.

However, even with a host of benefits for a Google-friendly HTTPS site, there are certain technical issues associated with its integration or maintenance that may puzzle even technical users. Let’s now talk about such issues and the best possible ways to resolve them.

Optimizing Speed and Performance

This article presented some tricky errors along with their easy, DIY solutions. Let us know in the comments if we’ve managed to keep the instructions clear and simple and if you performed all the steps accurately.

Optimizing Speed and Performance - Ruby on Rails vs PHP

It’s not uncommon to experience site performance/speed issues after upgrading to HTTPS. SSL-enabled sites go through a series of additional verification processes when a visitor enters. One of the key processes is the handshake that requires a significant amount of CPU power. Here are a few actionable tips that can minimize the operation series and resolve this issue.

  1. Save time by sending multiple requests through a single connection. For that purpose, you need to enable Keep-Alive connections.
  2. Shave time by reusing the SSL session parameters. It will eliminate the SSL handshakes requirements for subsequent or parallel connections.
  3. SSL session cache stores multiple sessions. This cache is shared between all the workers. Use ssl_session_cache directive to enable it.
  4. There are 4000 sessions per megabyte of cache and its default timeout is 5 minutes However, you can increase this time for the better results by using the directive ssl_session_timeout.
  5. To further enhance your website speed by 50-300%, you may also consider the downloadable Speed Kit extension on Plesk.

Issues regarding SSL certificates

Issues regarding SSL certificates - Plesk

SSL Certificate Chains

Another tricky situation is when browsers refuse to accept a certificate, even from a reputed authorized CA. The most popular browsers generally have an inbuilt certificate base containing variously authorized and reputed CAs. However, the reputed CAs use intermediate certificates to sign the server certificate.

The series of chained certificates are provided by the CAs that ultimately link to the root certificate. These intermediate certificates aren’t in the browsers’ inbuilt certificate store and it causes the error. Here are the actionable tips you can follow.

  1. Ideally, the chained certificates should follow the server certificates in order to enable the operations/process.
  2. If you’re non-technical, it’s good to get help from a professional or CA.
  3. Open certificate details and :certification path will reveal the problem areas.
  4. Communicate with your CA if you find difficulty installing an intermediate certificate.

Invalid SSL Certificate

If you try installing the certificate with incorrect details, you’ll get this error. Here’s what to do.

  1. Let’s Encrypt users can use the renewal command to renew an SSL certificate.
  2. If you purchased from another CA, ask them for an SSL certificate renewal.
  3. Make sure the CA is reputable and recognized by popular browsers.

Outdated SSL certificate

As the name suggests you need to renew your SSL certificate because it is now past its due date or has some validity issues. If your browser doesn’t support SNI, then updating its version can resolve the issue. You may also try revisiting the same page.

The Mixed Content Issue

When you use an HTTPS domain as a path to send HTTP elements, it causes the mixed content error. Basically, you’re trying to mix the different elements (HTTP and HTTPS) on the same platform. Here’s how to solve it.

  1. Just visit the console tab in chrome dev tools where you can find a series of elements. If the elements are hard-coded, you need to modify the URL manually. For external resources just replace the HTTP versions with HTTPS. If the external resources haven’t yet transferred to HTTPS, you can send them a request. Alternatively, you can also look for the HTTPS substitutes to the external resources, like images.
  2. Review the certificate information of the custom SSL certificate that you’re adding to CDN/Origin server and make sure all the information is correct and current. Things to check: intermediate certificates (check entire range  separately ), Private key, empty lines (delete if you encounter any).
  3. Use some reputable tool that can help generate an intermediate certificate.

Outdated Browser, Cache and Cookies

Older browsers may be unable to recognize the SSL-enabled sites because they don’t support these technologies. If browsers cache has saved the older SSL information about your site’s recently-updated certificate, then this message appears due to an info mismatch.

This error may still occur after you solve the problem. resolving the problem if that problem. The simple remedy is to clear your cache so your browser can again retrieve and read the updated certificate details.

Apache Issues

Apache Issues - Plesk

For Apache issues, you need to use codes. Digicert, leading SSL authority, provides a complete guide on how to resolve such issues. Along with solution codes that you might just need to copy/paste. With Digicert, you can also diagnose your SSL issues here, provide your site name and check for the reports.

Further DIY Solutions to HTTPS Issues in Plesk

If you love DIY exercises, then here are different ways to buy, manage or renew your SSL certificate in Plesk. All you have to do is to click the links below and follow the easy instructions.

  1. Change the default certificate
  2. Renew the default certificate
  3. Purchase SSL Certificate from Plesk
  4. Enable redirection from HTTP to HTTPS in Plesk
  5. Download SSL certificate in Plesk

This article presented some tricky errors along with their easy, DIY solutions. Let us know in the comments if we’ve managed to keep the instructions clear and simple and if you performed all the steps accurately.

arrow icon - Plesk

What is LAMP? LAMP stack basics to get you up and running fast

LAMP stacks

The LAMP stack has nothing to do with lighting, but it’s still a pretty bright idea (sorry, couldn’t resist!) It underpins many of the world’s most widespread open source web apps, like WordPress and Drupal, but its history goes back further than just being the bedrock of those currently popular platforms though. It’s one of the web’s original open source software stacks, and many developers still turn to it today when they are working on new custom web apps. As a developer you’ll find yourself running into it a lot too because it’s everywhere, and you’ll appreciate the fact that its uncomplicated and robust.

What is LAMP?

Glad you asked. LAMP stands for Linux, Apache, MySQL and PHP, and each one of them adds something unique to the development of high-performance web applications.

  • Linux: the LAMP Stack’s operating system. Linux started life in 1991. It’s an open source operating system and its free. It’s endured partly because it’s flexible and other operating systems are harder to configure. It’s used around the world and has proved itself in lots of different industries. So, it has a loyal fan base willing to shout its praises and help new users get up to speed.
  • Apache: the LAMP Stack’s web server. Apache HTTP Server is a free web server software package made available under an open source license. It used to be known as Apache Web Server when it was created in 1995. It offers a secure and extendable Web server that’s in sync with current HTTP standards.
  • MySQL: the LAMP Stack’s dbms. MySQL is a relational database management system used to store application data. It’s open source, and it lets you keep all your data in a format that can easily be queried with the SQL language. SQL works great with well-structured business domains and it’s a great workhorse that can handle even the largest and most complicated websites with ease.
  • PHP: the LAMP Stack’s programming language. PHP is an open source scripting language. It fits hand in glove with Apache to make building dynamic web pages a breeze. For instance, it steps into do what HTML can’t: enabling dynamic processes that involve pulling elements out of a database. PHP makes it easy to do tasks like this. You can add your code to the page at the part that you want to be dynamic, and hey presto! Job done. It’s an efficient and flexible language, and you can see the results of your new code as soon as you’ve written it. Just add it, hit refresh and it’s there. But if you’d prefer to use Perl or Python instead then you can, no problem. (Isn’t it handy that they both begin with the P?)

What is LAMP architecture like?

LAMP architecture is layered in the classic style, with Linux at the bottom, followed by Apache, MySQL, then PHP. Although PHP sits on the highest layer, it’s actually inside Apache.

How do the elements work together?

It all begins when someone’s browser sends a request for a web page to the Apache web server. If it’s for a PHP file, the request is forwarded to PHP, which loads the file and runs its code, then asks MySQL to fetch any information that the code may have referenced.

The code and the data it pulls up are used to create the output that lets browsers display webpages. The LAMP stack is good at delivering both static and dynamic pages, which is good because this is slightly more difficult to achieve because as the name suggests, dynamic content can change every time the page is loaded.

Once the file code has been run, PHP sends the data it produces back to the Apache web server, which then shunts it on to the browser, and this new data can also be stored in MySQL.

We haven’t mentioned Linux, but it’s the base on which all of this rests.

Flexibility

As the name suggests, the LAMP stack is based on Linux, but you could also use Windows if you needed to, which would give it the equally attractive title of a WAMP stack. You can swap in Mac OS to get a MAMP stack, or there’s even WIMP, which uses Windows and the Internet Information Services web server from Microsoft.

But the beauty of the LAMP stack is that all its components are free and open source, so you’re not tied in to use or pay for any of them. You just use what you need, when you need it.

The LAMP stack is flexible in other ways too. Apache has a modular design, so it’s possible to add on custom modules to extend functionality.

It’s also worth mentioning that the LAMP stack features enterprise-level encryption and security, so it’s “as safe as houses,” as they say.

Improving Efficiency – LAMP vs LEMP

The LAMP stack is a veteran that has been around for more than 10 years now, which means there are plenty of users who’ve been building modules for it for ages. The advantage of this is that whatever you might need to build for your own project, a lot of the work will have been done already. It’s great knowing that whatever you need, the work of others is waiting to help you cut down on your development time.

Another way to gain efficiency is by replacing Apache with NGINX, which is an is  an open-source high-performance web server is a web server which can also be used as a reverse proxy, mail proxy, load balancing solution and HTTP cache. NGINX focuses strongly on high concurrency, high performance and low memory use. Nowadays NGINX powers variety of high-load sites including Pinterest, Cloudflare, Airbnb, Netflix, Hulu, WordPress.com and GitHub.

What can go wrong without the best web hosting platform? [Infographic]

Without the right host for your website, a lot can go wrong for your business. Read on to learn more about the importance of choosing the right web hosting platform.

How important is choosing the right web host

Web Hosting Platform - infographic by Plesk

Choosing the right web hosting platform is as important as your site content. And the wrong web hosting platform can seriously impact your business. Your web host must protect your site from security breaches, and backup all your data in case of hacking.

Slow websites or ones that go down for even a few minutes will negatively impact your SEO ranking. (In this event, see how to turbocharge your website speed to get back on track.)

So how important is choosing the right web host? Let’s look at the facts.

One-second page load delay leads to 7% conversion drop

Load delay and conversion drop

Page loading time is one of the most important factors that contribute to your website’s success. Also, it affects whether visitors will return to your website and perform profitable or desired actions. According to Aberdeen Group, a 1-second loading delay can result in a 7% decrease in e-commerce conversions and can drop customer satisfaction by 16%.

Sites on Google’s page 1 load in under 2,000 ms

Sites on Google’s page 1 load in under 2,000 ms - Plesk

Websites that appear on Google’s first page of search results load in under 2,000 milliseconds and loading delays can result in a loss of 44.19% in page views for a 20 second loading delay. A slow-loading website isn’t likely to appear in the first page of Google’s results.

Need a mighty page speed boost? Check out Google Pagespeed Insights.

Almost half of websites are hosted on Apache servers

Apache servers - a majority

From all the billions of websites that exist on the internet, Apache servers are the most widely used with 46.9% of existing websites. NGINX is the second most popular with 37.8% of websites hosted on it. So, make sure your hosting platform supports this.

Stats for SMBs and large companies using private cloud

Stats for SMEs and large companies using private cloud - Plesk

Private cloud computing generally feels safer than public cloud computing because access to the resources in a cloud infrastructure is limited. However, many SMEs – about 8%, and even 24% of larger companies do not buy cloud infrastructure altogether. This is mainly because of lack of knowledge about cloud computing. Pick a web host with plenty of opportunities to scale to the cloud.

A whopping 86% of websites have serious security flaws

Whopping 86% of websites have serious security flaws - Plesk

Over 30,000 websites are hacked daily with 86% of websites having at least one serious security flaw, including these top brands.

Over half of WordPress sites run on an outdated CMS version

Over half of WordPress sites have outdated CMS version

One of the reasons why so many websites are hacked is because many of them run on an outdated CMS version. In fact, 56% of hacked WordPress sites, 84% of hacked Joomla sites, 96% of Magento sites and 81% of hacked Drupal were all hacked for the same reason.

Why Choose Plesk web hosting platform?

When it comes to choosing a web hosting platform, look for reliability and security more than anything. Want to offer users the ability to scale and grow your website quickly without compromising on quality? Then, a web hosting platform like Plesk is one of the best options to grow an enterprise website and maximize its potential.