WEB HOSTING SUPPORT NETWORK
     
 

How to use .htaccess files

What is an .htaccess file?

.htaccess files allow you to alter the default Apache web server configuration settings. They work recursively, so any defined configuration changes will be applied to the current directory and its subdirectories. The name of the file begins with a dot (.) symbol, and you can easily create .htaccess files via the File Manager section of the hosting Control Panel.

If you wish to edit an .htaccess file with a text editor of your choice, you can download the file via the hosting Control Panel > File Manager section or an FTP client. You can find step-by-step instructions on how to set up the most popular FTP clients in the Uploading files category from our online documentation. Some FTP clients do not show configuration/hidden files that start with a dot (.) symbol by default, so please refer to the official documentation of your FTP client of choice for instructions on how to show/display hidden files.

Most common uses of .htaccess files

In this article, you can find examples of the most common uses of .htaccess files listed below:

Note: With the introduction of Apache version 2.4+ and its Core Authorization module (mod_authz_core), the old Order, Deny, and Allow directives were deprecated by new directives like Require. There are compatibility issues when using the new and old directives simultaneously, and since a lot of software applications rely on the old directives, the examples in this article are listed with the old (but still fully functional) Order, Deny, and Allow directives.

How to protect a website with a password?

You can enable password protection for your website or a directory quite easily via the hosting Control Panel > Protection section > Web access protection subsection. More details about this option are available in our Password protection article.

Of course, you can enable this type of protection manually too:

• For Basic authentication (your username and password will be sent from your browser to our servers unencrypted):

  1. Use an online .htpasswd generation tool to generate your authentication username and hashed password pair.
  2. Insert the string generated by the .htpasswd generation tool into an .htpasswd file in the root folder of your domain (~/www/www/.htpasswd).
  3. Add this code block in the .htaccess file of your domain to enable the authentication:

    AuthType Basic
    AuthUserFile "/home/USERNAME/www/www/.htpasswd"
    AuthName Limited!
    require valid-user

    Note: You will need to replace USERNAME with your hosting account username.

• For Digest authentication (your username and password will be sent from your browser to our servers encrypted):

  1. Use an online .htpasswd generation tool that supports Digest authentication to generate your authentication username and hashed password pair.
  2. Insert the string generated by the .htpasswd generation tool inside an .htdigest file in the root folder of your domain (~/www/www/.htdigest).
  3. Add this code block in the .htaccess file of your domain to enable the authentication:

    AuthType Digest
    AuthDigestProvider file
    AuthUserFile "/home/USERNAME/www/www/.htdigest"
    AuthName Limited!
    require valid-user

    Note: You will need to replace USERNAME with your hosting account username.

How to fully disable public access to a website with an .htaccess file?

To entirely prevent access to your website, you can add the following code block to an .htaccess file located in the root folder of your domain (~/www/www/.htaccess):

Order Allow,Deny
Deny from all

If there are no .htaccess files with Order/Deny/Allow directives in the subdirectories of your website, the first line should be sufficient to prevent all visitors from accessing your website as it sets the default access state for your website to Deny.

Should you wish to allow your visitors to browse your website except for the contents of a specific subdirectory, add the code block listed above to an .htaccess file in that subdirectory.

How to prevent access to a website from specific IP addresses, networks, or domains?

The fastest way to prevent IP addresses or network from accessing your website is to block them via the hosting Control Panel > Protection section > Web access protection subsection. Details on how to use this option are available in our Block by IP article.

An .htaccess file can be used to block specific IP addresses, networks, and even domains from accessing a website with the Deny directive.

To block IP addresses (e.g. 1.2.3.4), networks (e.g. 5.6.7), domains (e.g. baddomain.com), or subdomains of another domain (e.g. anotherbaddomain.com) and prevent them from accessing your website, use this code block in an .htaccess file in the root directory of your website:

Order Deny,Allow
Deny from 1.2.3.4
Deny from 5.6.7.
Deny from baddomain.com
Deny from .anotherbaddomain.com
Allow from all

Note: For the domain rule to work properly, the domain needs to have a valid rDNS record which matches the IP address. This is because the web server does a reverse DNS lookup on the IP address to find the associated hostname, and then does a forward lookup on the hostname to assure that it matches the original IP address. Only if the forward and reverse DNS are consistent and the hostname matches, will the rule work.

In general, the last line can be skipped if you do not have other .htaccess files with defined Order/Deny/Allow directives. If you are not sure about this, we would recommend that you add it.

How to allow access to a website only from specific IP addresses, networks, or domains?

The process of allowing access to your website from IP addresses (e.g. 1.2.3.4), networks (e.g. 5.6.7), domains (e.g. baddomain.com), or subdomains (e.g. subdomain.anotherbaddomain.com) is similar to the access prevention listed above with some minor differences. To achieve this, add the following code block to the root .htaccess file of your website:

Order Deny,Allow
Allow from 1.2.3.4
Allow from 5.6.7.
Allow from baddomain.com
Allow from .anotherbaddomain.com
Deny from all

Note: For the domain rule to work properly, the domain needs to have a valid rDNS record which matches the IP address. This is because the web server does a reverse DNS lookup on the IP address to find the associated hostname, and then does a forward lookup on the hostname to assure that it matches the original IP address. Only if the forward and reverse DNS are consistent and the hostname matches, will the rule work.

If there are no .htaccess files in the subdirectories of your website with Order, Deny, or Allow directives, you can use this code block (changing the Order directive, and removing the Deny from all directive):

Order Allow,Deny
Allow from 1.2.3.4
Allow from 5.6.7.
Allow from baddomain.com
Allow from .anotherbaddomain.com


How to prevent access to a website from specific countries?

The easiest way to achieve this is to use the hosting Control Panel > Protection section > Web access protection subsection. More information about this feature is available in our Block by IP article.

You can prevent visitors from a specific country (e.g. Russia) from accessing a website by adding the following code block to your website:

SetEnvIf MM_COUNTRY_CODE "^RU$" CountryMatch
Deny from env=CountryMatch

If you want to block visitors from multiple countries (e.g. Russia and Antarctica), you can separate the two-letter country codes (ISO-3166-1 ALPHA-2) with a pipe symbol (|) in the .htaccess file as follows:

SetEnvIf MM_COUNTRY_CODE "^RU|AQ$" CountryMatch
Deny from env=CountryMatch

or add a separate line for each country as shown below:

SetEnvIf MM_COUNTRY_CODE "^RU$" CountryMatch
SetEnvIf MM_COUNTRY_CODE "^AQ$" CountryMatch
Deny from env=CountryMatch

Note: If a website visitor uses VPN or proxy services, their IP address and country will change, so your country blocks may result in false positives - bad actors may be able to access the website, and regular visitors may be prevented from accessing the website. For this reason, we would recommend that you use the country blocking option with care.

How to allow access to a website only from a specific country?

If you wish to prevent access to a website from all countries except for one (e.g. United States), you can add the following code block to the main .htaccess file of your website:

SetEnvIf MM_COUNTRY_CODE "^US$" CountryMatch
Allow from env=CountryMatch
Deny from all

If you want to allow access to your website from multiple countries (e.g. United States and Canada), you can separate the two-letter country codes (ISO-3166-1 ALPHA-2) with a pipe symbol (|) in the .htaccess file as follows:

SetEnvIf MM_COUNTRY_CODE "^US|CA$" CountryMatch
Allow from env=CountryMatch
Deny from all

or add a separate line for each country as shown below:

SetEnvIf MM_COUNTRY_CODE "^US$" CountryMatch
SetEnvIf MM_COUNTRY_CODE "^CA$" CountryMatch
Allow from env=CountryMatch
Deny from all

Note: You should use the country blocking option carefully as it may not work correctly for website visitors that use VPN or proxy services. For example, if a website visitor from the US uses a VPN service with IP addresses from outside of the US, the visitor will be unable to see your website.

How to prevent access to a website from specific browsers/User-Agents?

If you notice suspicious visits on your website generated from a specific browser/User-Agent, you can prevent it from accessing the website by using an .htaccess file. This option is very useful for bots that do not obey the robots.txt file and aggressively crawl websites.

The code block listed below will prevent visitors from accessing your website if their browser/User-Agent contains the "BadBot" string:

SetEnvIfNoCase User-Agent "BadBot" bad_bot
Deny from env=bad_bot

When blocking visitors based on User-Agent, you should carefully define the match string ("BadBot" in the example above) to ensure that there are no false positives. If you are not sure how to define the User-Agent, you can contact us for assistance.

Note: By default, we block access from browsers and bots that are known to be malicious or extremely aggressive. More details are available in our Error "412 Precondition Failed" (mod_security2) article.

How to block visitors referred from specific websites?

The hosting Control Panel > Protection section > Web access protection subsection allows you to easily block visitors coming from a specific website. You can learn more about this option in the Block referrers article.

To block visitors with a specific referrer (e.g. visitors coming from the website of baddomain.com), you can add the following code block to the main .htaccess file of your website:

RewriteEngine on
RewriteCond %{HTTP_REFERER} ^https?://(www\.)?baddomain\.com [NC]
RewriteRule .* - [F]

If you wish to block access to your website for visitors coming multiple websites (e.g. baddomain.com and subdomains of anotherbaddomain.com), you can insert the following lines to your website's .htaccess file:

RewriteEngine on
RewriteCond %{HTTP_REFERER} ^https?://(www\.)?baddomain\.com [NC,OR]
RewriteCond %{HTTP_REFERER} ^https?://([^.]+\.)*anotherbaddomain\.com [NC]
RewriteRule .* - [F]

If there are multiple RewriteCond directives listed one after the other, they all have to match for the RewriteRule directive to take place. For this reason, the OR flag is added to the first RewriteCond directive, so the RewriteRule directive will work if either of the RewriteCond directives matches. The NC flag indicates case insensitivity.

How to disable access to a file?

You can add an .htaccess file to the directory of a given file (e.g. private.txt) with the following code block to limit access to that file:

<Files "private.txt">
    Order Allow,Deny
    Deny from All
</Files>

The Files directive describes which file the given code block will be applied to. You can modify the code block within the Files directive to set custom access to the specified file.

Note: You can modify the lines within the Files directive to allow and/or prevent different IP addresses, networks, or domains from accessing the specific file.

How to disable access to multiple files?

If you wish to block public access to multiple files (e.g. private.txt and secret.doc), you can use the following FilesMatch directive in an .htaccess file located in the directory of the files:

<FilesMatch "^(private\.txt|secret\.doc)$">
    Order Allow,Deny
    Deny from all
</FilesMatch>

You can achieve the same result by enabling regular expressions for the Files directive with the tilde (~) symbol as shown in the example below; however, it is still recommended that you use the FilesMatch directive:

<Files ~ "^(private\.txt|secret\.doc)$">
    Order Allow,Deny
    Deny from All
</Files>

Note: You can modify the lines within the Files and FilesMatch directives to allow and/or prevent different IP addresses, networks, or domains from accessing the specific files.

How to disable access to multiple files with the same extension?

To block access to all files with the same extension (e.g. .txt), you can use the following code block in an .htaccess file:

<FilesMatch "\.txt$">
    Order Allow,Deny
    Deny from All
</FilesMatch>

If you want to prevent access to multiple file extensions (e.g. .txt, .doc, .rtf, .log, .fla, and .psd files), you should add the following lines to an .htaccess file:

<FilesMatch "\.(txt|doc|rtf|log|fla|psd)$">
    Order Allow,Deny
    Deny from all
</FilesMatch>

Note: You can modify the lines within the Files and FilesMatch directives to allow and/or prevent different IP addresses, networks, or domains from accessing the specific flies.

How to block access to a website in a specific time frame?

Using an .htaccess file, you can also restrict access to your website in specific time frames. For example, you can use this code in the .htaccess file of your website to disable public access between 7 PM and 7 AM, so your website will be available only between 7 AM and 7 PM:

RewriteEngine On
RewriteCond %{TIME_HOUR} >19 [OR]
RewriteCond %{TIME_HOUR} <07
RewriteRule ^.*$ - [F,L]

You can also disable access to a single file (e.g. contact.php) of your website for just an hour (e.g. starting from 1 PM):

RewriteEngine On
RewriteCond %{TIME_HOUR} ^13$
RewriteRule ^contact\.php$ - [F,L]

How to redirect your website from HTTP to HTTPS?

One of the easiest ways to force your website to use HTTPS instead of HTTP is via the hosting Control Panel. For WordPress, you can use the hosting Control Panel > WordPress Manager to update your SiteURL from HTTP to HTTPS as described in our Forcing HTTPS for WordPress article. For other applications, you can use the hosting Control Panel > SSL/HTTPS section > Force HTTPS subsection.

To redirect all requests to your website from HTTP to HTTPS with an .htaccess file, you can use the following code block:

RewriteEngine On
RewriteCond %{HTTPS} !on
RewriteRule (.*) https://%{HTTP_HOST}/$1 [L,R=301]

Note: The provided solution may not work for some software applications, so you should refer to the official documentation of the software application that you use for the best way to force the usage of HTTPS for your website.

If you encounter mixed content warnings while browsing your website, you may have to force the web server to load all elements of your website via HTTPS. For more information, you can refer to the How to force browsers to load all content from HTTP to HTTPS? section of this article.

How to redirect a website from the non-WWW version of your domain to the WWW version?

To get your website working with the WWW prefix (e.g. www.your_domain.com and not your_domain.com), you can use the following code block in an .htaccess file:

RewriteEngine On
RewriteCond %{HTTP_HOST} ^your_domain.com$
RewriteRule ^(.*)$ http://www.your_domain.com/$1 [L,R=301]

If you wish to test the redirect, you can use a 302 (temporary) redirect instead of a 301 (permanent) redirect to prevent possible browser caching issues. After you are sure the redirect is working correctly, you can change the redirect from 302 to 301.

Note: For some software applications, the provided solution may cause issues, so you should refer to the official documentation of the application you use. If you use WordPress, you can use the hosting Control Panel > WordPress Manager to change the URL of your website as explained in our Changing the Site URL article.

How to redirect a website from the WWW version of your domain to the non-WWW version?

To redirect visitors to your website without the non-WWW prefix (e.g. your_domain.com instead of www.your_domain.com), you can use the code listed below in your .htaccess file located in the website's root directory:

RewriteEngine On
RewriteCond %{HTTP_HOST} ^www.your_domain.com$
RewriteRule ^(.*)$ http://your_domain.com/$1 [L,R=301]

You should consider changing the redirect status code from 301 (permanent) to 302 (temporary) to test the redirect first. If everything is working as expected, you can set the redirect status code back to 301.

Note: If you are using a software application, you should refer to its official documentation on how to change the URL of your website. If you are running WordPress on your website, the easiest way to change the URL of your website is via the hosting Control Panel > WordPress Manager by following the instructions listed in our Changing the Site URL article.

How to redirect a website from the non-WWW version of your domain to the WWW version and forcing HTTPS?

You can add the following lines of code to your website's .htaccess file if you wish to have your website always working with HTTPS and the WWW prefix (e.g. https://www.your_domain.com):

RewriteEngine On
RewriteCond %{HTTP_HOST} ^your_domain.com$
RewriteCond %{HTTPS} on
RewriteRule ^(.*)$ https://www.your_domain.com/$1 [L,R=301]
RewriteCond %{HTTPS} !on
RewriteRule ^(.*)$ https://www.your_domain.com/$1 [L,R=301]

We encourage you to replace the 301 with 302 redirects in the above code when testing as this should prevent browser caching of the redirects. Do not forget to set the redirects to 301 once you are satisfied with the result.

Note: Some software applications may not work correctly with this redirection, so please refer to their official documentation for instructions on how to achieve the desired redirect. For WordPress, you can make the URL conversion from HTTP to HTTPS and from non-WWW to WWW at once by Changing the Site URL via the hosting Control Panel > WordPress Manager.

If mixed content browser warnings are displayed in your website, you may have to explicitly configure the server to upgrade all requests from HTTP to HTTPS. For more information, you can refer to the How to force browsers to load all content from HTTP to HTTPS? section of this article.

How to redirect a website from the WWW version of your domain to the non-WWW version and forcing HTTPS?

If you would like to have your website always working over HTTPS without the WWW prefix (e.g. https://your_domain.com), you can use the following .htaccess code:

RewriteEngine On
RewriteCond %{HTTP_HOST} ^www.your_domain.com$
RewriteCond %{HTTPS} on
RewriteRule ^(.*)$ https://your_domain.com/$1 [L,R=301]
RewriteCond %{HTTPS} !on
RewriteRule ^(.*)$ https://your_domain.com/$1 [L,R=301]

The 301 redirect is permanent and will allow your browser to cache the redirect, so you may use a temporary 302 redirect if you wish to test the redirect and make changes to the code.

Note: Redirect issues/loops can occur if you use the .htaccess code for some software applications. In such cases, you should refer to the official documentation of the software application installed on your website. If you are using WordPress, you can make the WWW to non-WWW and HTTP to HTTPS switch via the hosting Control Panel > WordPress Manager by Changing the Site URL of your WordPress installation.

Should your website show mixed content warnings, you should consider checking the How to redirect your website from HTTP to HTTPS? section of this article for a solution.

How to redirect a website to a specific page?

You can redirect all visitors of your website to a specific page (e.g. temp.php) by adding the following code block to an .htaccess file in the root directory of your website:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !temp\.php
RewriteRule .* /temp.php [NC,L,R=301]

Switching the redirect status code in the .htaccess file from 301 to 302 will allow you to test the redirection without having to worry about browser caching as the 302 redirections should not be cached by browsers. Do not forget to set the redirect status code back to 301 after the tests.

How to redirect a website to a maintenance page?

You can use the method listed above to display a temporary page to your website visitors. The only difference is that the redirect status code should be set to 302 or 307 which will indicate to browsers and search engines that the redirection is temporary.

Here is some sample code that you can use to redirect everyone visiting your website to a temporary maintenance page (e.g. maintenance.html) that resides in your website's directory:

RewriteEngine On
RewriteCond %{REQUEST_URI} !/maintenance.html$
RewriteRule .* /maintenance.html [L,R=307]

Note: Some software applications allow you to set a maintenance page via their administrative interface or by creating a file named ".maintenance" in the root directory of the application. If you use a software application, it is advisable that you check its documentation for instructions on enabling maintenance mode.

How to get a website to work from a subdirectory without showing it to visitors?

The easiest way to do get your website to load the files of a subdirectory (e.g. /new_subdirectory/) would be to change the document root of your website via the hosting Control Panel > Subdomains section as explained in our Document roots article. This way, your website files will be loaded from the specified subdirectory of your domain without it being shown in the URL of the website visitors.

You can achieve the same result by using the code listed below in an .htaccess file in the root directory of your website:

RewriteEngine On
RewriteCond %{ENV:REDIRECT_STATUS} ^$
RewriteRule ^new_subdirectory($|/) - [L,R=404]
RewriteRule !^new_subdirectory/ /new_subdirectory%{REQUEST_URI} [L]

How to get a website to work from a subdirectory and show it to visitors?

If you want to show your visitors that the website content has been moved to a subdirectory (e.g. your_domain.com/new_subdirectory/) and redirect them to the same page at the new location, you can do this with the following .htaccess file code block in the root directory of the website:

RewriteEngine On
RewriteCond %{REQUEST_URI} !^/new_subdirectory/
RewriteRule ^(.*)$ /new_subdirectory/$1 [NC,L,R=301]

The above code block will redirect visitors from any page of the main domain (your_domain.com/page.html) to same page in the specified subdirectory (your_domain.com/new_subdirectory/page.html).

If you simply wish to redirect all visitors to the index file of the new_subdirectory subdirectory, update the RewriteRule as follows:

RewriteRule .* /new_subdirectory/ [NC,L,R=301]
This way, visitors of your website will be redirected to the index file of the subdirectory (e.g. your_domain.com/new_subdirectory/).

How to redirect a website to another website?

To redirect a website to another website (e.g. another_domain.com), you can use the code block listed below in an .htaccess file located in the root directory of the website where the redirect will occur:

RewriteEngine On
RewriteRule ^(.*)$ https://another_domain.com/$1 [L,R=301]

This code will redirect visitors from any page of your website (e.g. your_domain.com/page.html) to the same page on the other website (e.g. another_domain.com/page.html). If you want to redirect all visitors without preserving the URL, use this .htaccess code block:

RewriteEngine On
RewriteRule .* https://another_domain.com/ [L,R=301]

How to redirect a page or directory to another one?

The easiest way to perform this type of redirects is via the hosting Control Panel > Redirect URL section.

If you wish to manually redirect a given page of your website to a new page of your or another website (e.g. old_page.html to new_page.html or old_file.html to http://another_domain.com/new_file.html), you can use the following code in an .htaccess file added to your website's root directory:

Redirect 301 /old_page.html /new_page.html
Redirect 301 /old_file.html http://another_domain.com/new_file.html

The same can rule can be used for directories (e.g. old_directory to new_directory or old_location to http://another_domain.com/new_location):

Redirect 301 /old_directory /new_directory
Redirect 301 /old_location http://another_domain.com/new_location

We would advise that you first set the redirects with a 302 (temporary) status code instead of 301 (permanent) as this will instruct browsers to not cache the redirection which will help ensure that your redirection is configured correctly. Once you are certain that the redirection is indeed configured correctly, you can set the redirect status code to 301.

How to force browsers to load all content from HTTP to HTTPS?

A browser will display a mixed content warning if you open a website via HTTPS, but some elements of the website (images, stylesheets, or other files) are actually loaded via HTTP. This poses a security issue as the connection is not fully encrypted.

To resolve this problem, you should first check that you have forced HTTPS for your website. You can refer to the How to redirect your website from HTTP to HTTPS? section of this article for more information.

If you still encounter the mixed content browser warning, it is possible that some remote elements are loaded via HTTP or some local elements are hard-coded to use HTTP. To fix this problem, you can force the web server to always request elements via HTTPS for the website by adding the following line to the .htaccess file of your website:

Header always set Content-Security-Policy: upgrade-insecure-requests

How to enable HSTS?

HTTP Strict Transport Security (HSTS) is a simple policy which protects website visitors by ensuring that their browsers always connect to a website over HTTPS. HSTS removes the need to use common techniques for redirecting users from http:// to https:// URLs.

Before you enable HSTS, you should first check that you have not forced HTTPS for your website via the hosting Control Panel > SSL/HTTPS section > Force HTTPS subsection. Forcing HTTPS this way may affect the proper operation of the HSTS-enabling lines in your .htaccess file. Also, make sure you have not forced a redirect from non-www to www via your hosting Control Panel > Domain Parking section > Domain Redirects tab. Furthermore, you should check your .htaccess file for other custom rewrite rules and remove them, if they are related to or in conflict with the HSTS directive.

To summarize, the main requirements of HSTS are:

1) redirect from HTTP to HTTPS on the same host. i.e. http://example.com to https://example.com and http://www.example.com to https://www.example.com;

2) redirect to the canonical hostname (www or non-www) on HTTPS only. (i.e. after #1 above);

3) send the Strict-Transport-Security (STS) HTTP response header when on HTTPS only, including on the canonical redirect (#2 above).

To enable HSTS for your website and set up a redirect from non-www to www at the same time, add the following lines to your .htaccess file (the order of the lines is important):

RewriteEngine On

# Set HSTS env var only if HTTPS
RewriteCond %{HTTPS} on
RewriteRule ^ - [E=HSTS:1]

# Redirect HTTP to HTTPS on the same host
RewriteCond %{HTTPS} !=on
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

# Redirect non-www to www (HTTPS only)
RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^ https://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

# Set HSTS header for 365 days including subdomains conditionally if request is over HTTPS only (based on HSTS env var)
Header always set Strict-Transport-Security "max-age=31536000; includeSubDomains; preload" env=HSTS

If you prefer using non-www URLs instead of www, you can add the following lines instead:

RewriteEngine On

# Set HSTS env var only if HTTPS
RewriteCond %{HTTPS} on
RewriteRule ^ - [E=HSTS:1]

# Redirect HTTP to HTTPS on the same host
RewriteCond %{HTTPS} !=on
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

# Redirect www to non-www (HTTPS only)
RewriteCond %{HTTP_HOST} ^www\.
RewriteRule ^ https://your-domain-name.com%{REQUEST_URI} [R=301,L]

# Set HSTS header for 365 days including subdomains conditionally if request is over HTTPS only (based on HSTS env var)
Header always set Strict-Transport-Security "max-age=31536000; includeSubDomains; preload" env=HSTS

When redirecting from www to non-www URLs, make sure to replace your-domain-name.com with your actual domain name.

HSTS is a nice addition to loading all website elements via HTTPS, as described in the How to force browsers to load all content from HTTP to HTTPS? section of this article.

How to take advantage of browser caching?

One of the best ways to reduce the loading time and traffic usage of your website is to help browsers identify what information can be cached and for how long. You can use the following code block in an .htaccess file inside your website to instruct browsers to cache images, stylesheets, and JavaScript files.

ExpiresActive On
ExpiresByType application/javascript "access 1 month"
ExpiresByType application/pdf "access 1 month"
ExpiresByType application/x-javascript "access 1 month"
ExpiresByType application/x-shockwave-flash "access 1 month"
ExpiresByType image/gif "access 1 year"
ExpiresByType image/jpeg "access 1 year"
ExpiresByType image/jpg "access 1 year"
ExpiresByType image/png "access 1 year"
ExpiresByType image/x-icon "access 1 year"
ExpiresByType text/css "access 1 month"
ExpiresDefault "access 2 days"

How to enable content compression?

Another great way to reduce the loading time of your website and your traffic usage is to enable compression support for your website. When compression is enabled and a visitor opens your website, the web server will send a request to the browser of the visitor to check if compression is supported. If it is supported, the web server will compress all data that is defined for compression and send the compressed data to the visitor's browser. The browser will decompress the data, and the original content file will be loaded. This happens automatically and will be invisible to the visitor. The visitor will only benefit from faster loading time and reduced data usage.

Most modern browsers have full support for Brotli, Deflate, and GZIP compression. On our servers Brotli (mod_brotli) and Deflate (mod_deflate) compressions are supported, and GZIP compression (mod_gzip) is covered by the Deflate compression (mod_deflate). The compression can be enabled via an .htaccess file.

To enable Brotli compression on your website for HTML, SSI, PHP, Perl, Ruby, Python, CGI, CSS, JavaScript, and text files, you need to place the following code block inside an .htaccess file in the root folder of your website:

<IfModule brotli_module>
    AddOutputFilterByType BROTLI_COMPRESS text/css text/csv text/html text/plain text/richtext text/sgml text/tab-separated-values application/javascript application/x-javascript httpd/unix-directory
</IfModule>

To get Deflate compression enabled on your website for HTML, SSI, PHP, Perl, Ruby, Python, CGI, CSS, JavaScript and text files, you should add the following lines to your website's .htaccess file:

<IfModule deflate_module>
    AddOutputFilterByType DEFLATE text/css text/csv text/html text/plain text/richtext text/sgml text/tab-separated-values application/javascript application/x-javascript httpd/unix-directory
    AddOutputFilter DEFLATE html htm shtml php php4 pl rb py cgi css js txt
    BrowserMatch ^Mozilla/4 gzip-only-text/html
    BrowserMatch ^Mozilla/4\.0[678] no-gzip
    BrowserMatch \bMSIE !no-gzip !gzip-only-text/html
</IfModule>

How to set custom error pages?

With an .htaccess file you can display custom error pages to your website visitors when the server returns an error. This is possible with the ErrorDocument directive. The syntax you should use is:

ErrorDocument error_number custom_error
You should replace error_number with the exact number of the error that you wish to set a custom error page for. The custom_error can be replaced with a single word, quoted text message with HTML support, a local file, or a URL.

Here is sample .htaccess code that will display a single word/string without intervals (e.g. Error!) in the body of the page to the visitor when they try to open a page that does not exist and the server returns error 404:

ErrorDocument 404 Error!
If you wish to display a more helpful message that is longer than one word/string, you should surround the message text in quotes. HTML is also supported, so you can define a custom 403 error message by using the following line in your website's .htaccess file:

ErrorDocument 403 "<html><title>Forbidden!</title><body>You don't have permission to access this resource.</body></html>"
The ErrorDocument directive also allows you to direct visitors to a local file (e.g. /path_to/custom_404_error_page.php) when they encounter a specific error (e.g. 404). You can achieve this by adding the following line to your .htaccess file:

ErrorDocument 404 /path_to/custom_404_error_page.php
You can also redirect visitors to a remote website/page (e.g. http://another_domain.com/custom_500_error_page.html) when they encounter an error on your website (e.g. 500). Here is the exact line that you need to add to the .htaccess file of your website for this:

ErrorDocument 500 http://another_domain.com/custom_500_error_page.html

How to change the default browser behavior for specific files/types?

Browsers can handle files differently based on their extension. By default, most modern browsers can be used to directly view PDF files or view and listen to music and video files. The default behavior may be altered within the browser's settings in some cases which is from the perspective of a website visitor. However, as a website owner, you can also change this behavior and instruct the browser how to handle specific files (e.g. display download prompt for MOV, MP3, MP4, and PDF files, so they cannot be viewed directly in the browser) by adding a code block like the following in the .htaccess file of your website:

<FilesMatch "\.(mov|mp3|mp4|pdf)$">
    ForceType application/octet-stream
    Header set Content-Disposition attachment
</FilesMatch>

How to enable directory listing?

Directory listing is disabled by default on our servers for security concerns, and it can be enabled only for directories without an index file. So, to enable directory listing for a specific location, you need to remove any index files and add the following code block to an .htaccess file within the directory location on the server:

Options +Indexes
Note: Please enable directory listing with care as this will allow anyone (including visitors with malicious intentions) to view your files and directory structure.

How to hide specific files from directory listing?

If you have enabled directory listing as explained above but wish to prevent visitors from viewing specific files (e.g. PHP and JS files), you can add the following line to your .htaccess file:

IndexIgnore *.php *.html

How to disable directory listing?

Directory listing is disabled on our servers by default. If it is enabled for some reason (e.g. it is enabled for an upper directory), you can disable it by creating/uploading an index file to the said directory or create an .htaccess file with the following line in it:

Options -Indexes

How to prevent hotlinking of your images?

The term "hotlinking" refers to the use of elements (mostly images) from one website on another website. Hotlinking was very popular in the past as traffic limits were pretty restrictive, and it allowed website owners to display images on their website without taking a hit on their traffic usage. However, this was causing issues for the websites where the images were actually hosted as they would generate traffic quickly without actually having any visitors.

Nowadays hotlinking is not so popular, but it is possible to experience its negative effect. If you wish to prevent third parties from using images of your website, you can add the following code block to an .htaccess file inside the root directory of your website (e.g. your_domain.com):

RewriteEngine On
RewriteCond %{HTTP_REFERER} !^http://(www\.)?your_domain\.com/ [NC]
RewriteCond %{HTTP_REFERER} !^$
RewriteRule \.(jpeg|JPEG|jpe|JPE|jpg|JPG|gif|GIF|png|PNG|tif|TIF|tiff|TIFF)$ - [F]

If you have domains parked to your account, you should use the following code block in your website's .htaccess file, so that not only the main domain (e.g. your_domain.com), but also the parked domains (e.g. your_first_parked_domain.com and your_parked_domain_2.com) can display the images as well:

RewriteEngine On
RewriteCond %{HTTP_REFERER} !^http://(www\.)?your_domain\.com/ [NC]
RewriteCond %{HTTP_REFERER} !^http://(www\.)?your_first_parked_domain\.com/ [NC]
RewriteCond %{HTTP_REFERER} !^http://(www\.)?your_parked_domain_2\.com/ [NC]
RewriteCond %{HTTP_REFERER} !^$
RewriteRule \.(jpeg|JPEG|jpe|JPE|jpg|JPG|gif|GIF|png|PNG|tif|TIF|tiff|TIFF)$ - [F]

How to add Content-Type headers?

You can instruct the browsers of your website's visitors to use a specific character set for your website with the AddDefaultCharset .htaccess directive. For example, you can define the default character set (e.g. UTF-8) for your website in an .htaccess with the code listed below, so browsers will automatically use this character set:

AddDefaultCharset UTF-8

How to make URLs case-insensitive?

Our servers run Linux, which is a case-sensitive system. For example, if you have a page named "test.html" on the server, browsing a page named "Test.html" will result in a 404 (Not Found) error.

The case sensitivity can be disabled with the mod_speling Apache module on our servers. To do this, simply add the following code block to the .htaccess file of your website:

<IfModule mod_speling.c>
    CheckSpelling on
    CheckCaseOnly on
</IfModule>

If your server does not support mod_spelling, you can refer to the .htaccess solution for rewriting all URLs to lower case at www.askapache.com.

How to trim the extensions of pages/files?

There are multiple ways to hide the extensions of your website's files. For example, to hide the ".php" extension of PHP files, you can add the following line to your website's .htaccess file:

Options +FollowSymLinks
RewriteEngine On
RewriteCond %{REQUEST_METHOD} !POST
RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s([^.]+)\.php [NC]
RewriteRule ^ %1 [R=302,L,NE]
RewriteCond %{REQUEST_FILENAME}.php -f [NC]
RewriteRule ^ %{REQUEST_URI}.php [L]

Another method to hide the extension of your files is the Multiviews option which is supported by default on our servers. If a visitor of your website tries to open up a page that doesn't exist (e.g. a "page" without an extension), but there is a file with that name (e.g. "page.html'), the web server will serve the existing file to the visitor as if the existing file was requested (e.g. "page.html"). Please note that with this method, visitors will still be able to access the original file if they open it directly.

If Multiviews is not enabled for your website, you can enable it by adding the following line to your website's .htaccess file:

Options +MultiViews

How to insert a comment in an .htaccess file?

Lines in .htaccess files that begin with a shebang (#) symbol are considered comments and will be ignored by the web server. So, to insert a comment or comment a specific directive in an .htaccess file, all you need to do is add a shebang symbol at the start of the line. For example, here are two valid .htaccess comments:

#This is a comment.
      #Options +MultiViews - This directive is correctly commented out.

Here is one invalid comment example that will most likely cause your website to return a 500 Internal Server Error:

Options +MultiViews #This is an invalid comment.