.htaccess

Editor: Anna Belous 1986 7 min Audio

What is .htaccess?

The .htaccess (hypertext access) file is used as one of the means for simple and comfortable Apache webserver configuration. Hence, changing the webserver setup will allow changing the website’s operation. htaccess is usually located in the root catalogue and influences all of its sub-catalogs and the website. If there is another .htaccess file in another catalogue, it will only influence the catalogue in question and it’s sub-catalogs.

Note! Making changes to the .htaccess file may seriously disrupt the website’s functioning. Any mistake with changing the file may cause serious consequences up to decrease or complete loss of search engine ranking of the website while not having visible consequences on the website’s performance. This is why creating a backup copy of it before taking any action is recommended.

Where is the .htaccess file located?

It is usually located in the root catalogue. You can find htaccess.txt located in some CMSs instead of .htaccess. This file has no influence on the server and is not actively used. For the file to work properly, you need to change the file extension to .htaccess. If that is not possible from your computer, log in to your server via FTP client and rename the file on the server directly.

You can edit the file on your computer with any text editor, although we do advise Notepad++ to avoid any issues.

How to check if .htaccess is working?

Simply type any random word in the first text line of the file, save it and replace the one that is currently on the server with it. If the website is still functioning in the usual way - .htaccess is not working. If you get an Internal Server Error 500, the webserver wasn’t able to process the command (the random word). This will confirm that .htaccess file is up and running at the moment. To get the website back up simply remove the random word.

We’ll look through the useful features of the file further on.

  1. Redirect between pages or websites+URL change
  2. Error processing
  3. Website security setup
  4. Website pages encoding
  5. Website optimization
  6. PHP setup

Proper 301 redirect setup using .htaccess file

Note! If you want for your redirect to function, make sure you type ‘RewriteEngine On’ before the strings provided below.

RewriteEngine On

301 Redirect to a different page or website

Enter the following lines in the .htaccess file:

Redirect 301 /oldpage.html http://website.com/newpage.html

or

RedirectPermanent /oldpage.html http://website.com/newpage.html

301 Redirect from www subdomain to domain or redirect from www.site.com to your site.com

E.g. From http://www.site.com to http://site.com. It’s quite useful and commonly used in SEO

Options +FollowSymLinks
RewriteEngine On
RewriteCond %{HTTP_HOST} ^www.domain\.com$ [NC]
RewriteRule ^(.*)$ http://domain.com/$1 [R=301,L]

Reverse redirect from a ‘non-www’ to a ‘www’ address

Redirect from http://site.com to http://www.site.com (we do not advise using this one)

Options +FollowSymLinks
RewriteEngine On
RewriteCond %{HTTP_HOST} ^domain\.com$ [NC]
RewriteRule ^(.*)$ http://www.domain.com/$1 [R=301,L]

Redirecting all users from the old website to a new one

Redirect 301 / http://newsite.com/

How to add .html at the end of a URL?

If you want for the user to be transferred to site.com/page.html once they enter site.com/page or site.com/page/ enter the following text in the .htaccess file:

RewriteCond %{REQUEST_URI} (.*/[^/.]+)($|\?)
RewriteRule .* %1.html [R=301,L]
RewriteRule ^(.*)/$ /$1.html [R=301,L]

How to remove.html at the end of the URL?

Reverse redirect from site.com/page.html to site.com/page

RewriteBase /
RewriteRule (.*)\.html$ $1 [R=301,L]

How to remove forward slash at the end of the URL?

E.g. site.com/page/ to site.com/page

RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.+)/$ /$1 [R=301,L]

301 Redirect from one section of the website to another

Redirecting all the pages from one section of the site site.com/section-1/section-2/page to another site.com/section-1/page

RewriteRule ^blog/random/(.*)$ http://site.com/blog/$1 [R=permanent,L]

301 Redirect when you move to another domain name

The following lines entered in .htaccess file will redirect the users from each specific page of the old website to the corresponding one on the new website. For example to redirect oldsite.com/page to newsite.com/page

RewriteCond %{HTTP_HOST} ^www.oldsite.com$ [NC,OR]
RewriteCond %{HTTP_HOST} ^test.oldsite.com$ [NC]
RewriteRule ^(.*)$ http://newsite.com/$1 [R=301,L]

Error page editing via .htaccess

When the user loads the website (sends a request to hoster’s server) the server returns a response with a code. Codes 1-399 mean that the server is working properly and 400-599 mean a server error (here’s our article on server error codes).

If for example, the server hosting your website is overloaded, it will reboot and the user will see the error page with a certain text (like 500 Internal Server Error). He might think that the website is no longer operational and never return. A commonly used solution is to create a custom error page instead of standard 404 Error one. This error informs the user that the page with the URL he entered doesn’t exist.

Experienced webmasters create a page of their own instead of the default one. It says that the person followed a link that doesn’t exist and offers to search for the necessary information on the website instead of just leaving. You can check out our 404 page as an example here. To display your custom error page instead of the default one, you need to create a separate page (e.g. http://yoursite.com/404.html) and add corresponding code to .htaccess file. Here are some code examples that you might want to add:

ErrorDocument 400 http://yoursite.com/400.html
ErrorDocument 404 http://yoursite.com/404.html
ErrorDocument 500 http://yoursite.com/500.html

If you want a different page instead of 403 Error (access denied) you will also need to write a text message that will be displayed, for example:

ErrorDocument 403 "Sorry can't allow you access today, see you later alligator :)"

Website security setup via .htaccess file

The .htaccess file gives some opportunities to improve website security. Here are the most popular ones:

Protecting your website against script injections

#Enables sym (symbolic) links tracking
Options +FollowSymLinks
#Runs url_rewriting
RewriteEngine On
#Blocks all links containing<script>
RewriteCond %{QUERY_STRING} (\<|%3C).*script.*(\>|%3E) [NC,OR]
#Blocks all scripts that attempt to change PHP Globals variables:
RewriteCond %{QUERY_STRING} GLOBALS(=|\[|\%[0-9A-Z]{0,2}) [OR]
#Blocks all scripts that attempt to change _REQUEST variable:
RewriteCond %{QUERY_STRING} _REQUEST(=|\[|\%[0-9A-Z]{0,2})
#Redirects all similar attempts to 403 Error page – denied
RewriteRule ^(.*)$ index.php [F,L]

This setup is rather a component of website security then a 100% guarantee.

Protection from image stealing

Some dishonest webmasters might find out the path to the image on your website and enter it in their page script. The main page of their website then loads from their server and the image - from yours. That allows them to save their traffic and use yours instead.

Options +FollowSymlinks
#Blocks image theft
RewriteEngine On
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^http://(www.)?yoursite.com/ [nc]
RewriteRule .*.(gif|jpg|png)$ http://yoursite.com/images/stop_stealing.gif[nc]

Restricting access by IP address

Used against spammers and other unwelcome guests and rarely - to prevent hacker attacks

#Entering IP’s to ban this way
allow from all
deny from 164.186.15.116
deny from 124.153.34.144

Blocking all IPs apart from the trusted ones

To block access to your website from all IPs except from specific ones, you need to add the following code:

#Restricts access for all but listed
ErrorDocument 403 http://www.yoursite.com
Order deny,allow
Deny from all
Allow from 164.186.15.116
Allow from 124.153.34.144

Restricting access to specific folder

#Restricts specific folder content review
Options All -Indexes

Restricting access to specific file

#Protects file myfile.txt
<files myfile.txt>
order allow,deny
deny from all
</files>

Restricting access to all files with a specific extension

For example, to restrict access to all .txt files you need to enter the following:

<Files "\.(txt)$">
Order Deny,Allow
Deny from all
</Files>

Blocking unneeded user agents

Usually there are a lot of extensions installed in your browsers. These extensions transmit information to the server that hosts your website. Same information is sent by user applications installed on the user's PC and all sorts of robots and spiders.

#Blocks all User Agents listed below
SetEnvIfNoCase user-Agent ^FrontPage [NC,OR]
SetEnvIfNoCase user-Agent ^Java.* [NC,OR]
SetEnvIfNoCase user-Agent ^Microsoft.URL [NC,OR]
SetEnvIfNoCase user-Agent ^MSFrontPage [NC,OR]
SetEnvIfNoCase user-Agent ^Offline.Explorer [NC,OR]
SetEnvIfNoCase user-Agent ^[Ww]eb[Bb]andit [NC,OR]
SetEnvIfNoCase user-Agent ^Zeus [NC]
<limit get="" post="" head="">
Order Allow,Deny
Allow from all
Deny from env=bad_bot
</limit>

Changing website encoding via .htaccess

The website content might be displayed normally for some users and in the form of unknown symbols instead of letters for the other. The reason for this is incorrectly set up website encoding.to ensure that all browsers load the website content correctly, the website uses one of the popular encodings:

  • UTF-8 - universal two-byte encoding
  • Windows-1251 - Cyrillic (Windows)
  • cp866 – Cyrillic (DOS)
  • Windows-1250 – Central Europe (Windows)
  • Windows-1252 – Western Europe (Windows)

The encoding should also be mentioned in every page’s meta tag for the browser to know using which encoding is the page created in:

<meta http-equiv="content-type" content="text/html; charset=Windows-1251">

If the above-mentioned meta tag is not added, you can inform the browser about your website encoding using the .htaccess file:

AddDefaultCharset WINDOWS-1251

In case both meta tag and .htaccess are working, it is important for the encoding to match.

It is also possible for the server to encode all of the files added to it automatically by adding this line:

CharsetSourceEnc WINDOWS-1251

To disable this feature you need to enter:

CharsetDisable on

Website optimization via .htaccess

Compressing files using gZip

Enabling this utility allows the server to compress the data before sending it to the user. Bottom line is that you increase the website speed at the expense of some extra server load since it will have to compress the data. You need to add some code to enable gZip in your .htaccess file. Try adding each of the 3 following versions and check the speed boost for each here. We will much appreciate a comment with your experience on the effectiveness of those.

<IfModule mod_deflate.c>
AddOutputFilterByType DEFLATE text/html text/plain text/xml application/xml application/xhtml+xml text/javascript text/css application/x-javascript
BrowserMatch ^Mozilla/4 gzip-only-text/html
BrowserMatch ^Mozilla/4.0[678] no-gzip
BrowserMatch bMSIE !no-gzip !gzip-only-text/html
<ifmodule mod_gzip.c>
mod_gzip_on Yes
mod_gzip_item_include file \.js$
mod_gzip_item_include file \.css$ </ifmodule>
</IfModule>

or

FileETag MTime Size
<ifmodule mod_expires.c>
<filesmatch ".(jpg|jpeg|gif|png|ico|css|js)$">
ExpiresActive on
ExpiresDefault "access plus 1 month"
</filesmatch>
</ifmodule>

or

<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>

How to improve website caching on the server?

Improved caching allows to pull up the data from the user’s PC instead of loading it from the server each time (images, main design elements, etc.) which user already loaded when he first entered the website. Hence, for each specific user, the second and each following time he enters the website it will load faster and the load on your server will decrease significantly. Improved caching can be enabled by entering one of the two codes below. Try each and test the speed here. We will much appreciate a comment with your experience on the effectiveness of each.

<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType application/javascript "access plus 7 days"
ExpiresByType text/javascript "access plus 7 days"
ExpiresByType text/css "access plus 7 days"
ExpiresByType image/gif "access plus 7 days"
ExpiresByType image/jpeg "access plus 7 days"
ExpiresByType image/png "access plus 7 days"
</IfModule>

or

FileETag MTime Size
<ifmodule mod_expires.c>
<filesmatch ".(jpg|gif|png|css|js)$">
ExpiresActive on
ExpiresDefault "access plus 1 month"
</filesmatch>
</ifmodule>

TTL (Time to Live) is a specific setting that allows to set the timeframe of each chunk of data to stay cached. Once that preset time elapses the data will be deleted and a new query will be performed. You can set the TTL for the files on the user’s computer in the “access plus …” line. Once expired, these files will be loaded again once the user enters the website. 7 days to 1 month timeframes are considered to be optimal but sometimes are set up to 1 year.

Changing the index page of the website

When a user loads your website, index.html or index.php is the first page to load. To change the page add this code to the .htaccess file (so now mypage.php will load first):

DirectoryIndex about.html

PHP settings configuration via .htaccess

Note! Using any of the directives for PHP setup depends on the PHP version that is installed on the server and the restrictions of the hosting company. Hence, if a directive didn't work or its usage caused a website error (and you are sure it was used correctly), you might want to contact the hosting company's tech support and specify the reason why the error occurred and the ways of correcting it.

The php.ini file contains all of the PHP settings. However, some of those settings can be configured in the .htaccess file. You should use php_flag for booleans (true/false) and php_value for digital values. Here are the rules to those:

php_flag directive1 VALUE1
php_value directive2 VALUE2

Where VALUE 1 can be on, off, 1 or 0 (1 and on stand for turning on, 0 and off for turning off);

VALUE2 is any digital or string value that suits a specific directive;

directive1 (used with php_flag only) can have the following values:

magic_quotes_gpc

- magic_quotes_gpc function on/off

php_flag magic_quotes_gpc on

Note!This directive is considered to be outdated and was turned off for PHP versions 5.4.0 and higher.

display_startup_errors

- PHP errors displaying on/off

php_flag display_startup_errors 1

display_errors

- browser error displaying on/off

php_flag display_errors 1

output_buffering

- output data buffering on/off

>php_flag output_buffering on

register_globals

- global variables on/off

php_flag register_globals on

engine

- PHP execution in .htaccess folder and subfolders on/off

php_flag engine off

directive2 (used with php_value only) can have the following values:

upload_max_filesize

- sets maximum size for uploaded files

php_value upload_max_filesize 10M

user_agent

- sets user_agent value passed by the server

php_value user_agent “Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)”

post_max_size

- sets maximum size of sent mail

php_value post_max_size 10M

mysql.default_user

- sets name for database user

php_value mysql.default_user databaseuser

mysql.default_password

- sets password for database user

php_value mysql.default_password jk323jh4g

mysql.default_host

- sets host name for database (usually it’s localhost)

php_value mysql.default_host localhost

sendmail_from

- sets address to send email using PHP php_value sendmail_from

php_value sendmail_from

auto_prepend_file

- sets file that will be added in the beginning of each PHP script

php_value auto_prepend_file /www/publiс_html/myfile.php

auto_append_file

- sets file that will be added in the end of each PHP script

php_value auto_append_file /www/publiс_html/myfile.php

Note! Not all hosting companies allow making changes to PHP settings via .htaccess. We advise specifying this matter with tech support.

Some hints for working with the .htaccess

Since .htaccess file allows to change some of the hosting server settings we advise checking with their support (or read their FAQ) regarding the usage of certain directives.

The hosting provider might restrict or substitute some directives depending on the Apache version.

For example, some hosting providers forbid using ‘strtoupper’ function that converts a string to the upper case because it significantly increases the webserver load.

You might want to check the following directives as well:

Options +FollowSymLinks can be substituted by Options +SymLinksifOwnerMatch
Options All-Indexes can be substituted by Options-Indexes

Some directives might not be used by a specific Apache version, hence they should be deleted or commented.

You can comment on a directive by placing # at the beginning of the string.

Due to this we strongly recommend studying the directives available for .htaccess file setup. It will help to avoid an error message related to .htaccess instead of a loaded website.

Anna Belous
Only experts answer your questions
Did not find an answer to your question?
Ask the experts! Answers are quick and go directly to your email.

Adding confirmation "I'm not a robot" you also agree to receive messages from hostings.info and accept its Privacy Policy, allowing hostings.info to store and process your personal information indicated above to provide requested content.

Ratings of hosting providers by site tasks
Hosting price

We highly recommend not to purchase the cheapest hosting package. Usually, they come with a row of issues: the server is often down, the hardware is outdated, lousy and slow support, registration and payment errors, etc.

For your convenience, we have created a tool that can help you to choose the right hosting package for you just by answering a few simple questions.

CMS

CMS is a content management system. A lot of hosting providers offer so-called CMS optimized packages. However, this is a marketing trick because most CMSs do not have special software or hosting requirements.

Free trial

Trial period is a period of time, usually from 7 to 30 days, during which you can use the hosting services for free to test them.

Moneyback policy allows the customer to receive a refund for his order within a certain period after the purchase.

OS

OS means the operating system is installed on the server. We recommend to choose Linux hosting unless your website requires another OS.

Other

Bulletproof hosting - it’s a type of service that allows to host almost any type of content, even the restricted one (adult content, warez, spam etc). Bulletproof hosting providers do not remove your content in case someone reports an abuse.

Unlimited hosting - refers to companies that provide packages with unlimited disk space, bandwidth, number of domains, databases or email accounts, etc. This is usually a marketing trick but sometimes you can find something worth a try.

Secure hosting - it’s a type of service when the hosting provider is mostly responsible for the security of the user’s account: updates the software installed on their servers, provides an antivirus and malware scanner, firewalls and basic anti-DDoS protection, etc.

DDoS-protected hosting - companies that provide packages that include anti-DDoS protection. These packages are considerably more expensive than regular ones. Nevertheless, they’re totally worth their price because the company will ensure that your website is secured from cyber attacks.

Technologies

Most websites require MySQL and PHP installed on the server to work correctly. Almost all hosting providers support these technologies.

ASP.NET is a Microsoft web application development platform.

Control panel

The more comfortable the control panel is, the easier will it be for you to change the website and hosting account settings.

Most hosting providers that are in TOP20 in our rating offer user-friendly control panels, such as cPanel, Plesk or DirectAdmin. That’s why we recommend to pay attention to other, more important parameters, while choosing a hosting provider.

Disk type