.htaccess Guides and Tutorials

.htaccess guide

Introduction

.htaccess is a configuration file for use on web servers running the Apache Web Server software. When a .htaccess file is placed in a directory which is in turn 'loaded via the Apache Web Server', then the .htaccess file is detected and executed by the Apache Web Server software. These .htaccess files can be used to alter the configuration of the Apache Web Server software to enable/disable additional functionality and features that the Apache Web Server software has to offer. These facilities include basic redirect functionality, for instance if a 404 file not found error occurs, or for more advanced functions such as content password protection or image hot link prevention.


Error Documents

Error documents are important, it allows you to show web visitors a friendly error message, an example would be a URL if the website is not working or if a user typed in a wrong url.

To setup a custom error page document, create an .htaccess file with the following text:

ErrorDocument 404 /error_pages/404.html

This will show 404.html error page whenever a 404 (file not found) error occurs.

Some other types of error documents are as follows:

ErrorDocument 401 /error_pages/401.html
ErrorDocument 401 /error_pages/403.html
ErrorDocument 500 /error_pages/500.html

Error 401 (Unauthorized) or 403 (forbidden) or error 500 (internal server error) can be used to display pages to website visitors.


Redirect

Redirect allows us to direct website visitors from ane document to another. This is useful if you are serving static pages and would like to update your visitors to a new file.

Redirect /old_dir/ http://www.yourdomain.com/new_dir/index.html

the above line explains that if the visitor requests a document in the 'old_dir', they will be redirected to the 'new_dir'.

The old_dir may contain more than one file or another directory, since we are referring to a directory, any file requested by the user inside the old_dir will redirect the user to the new one.


Password Protection

Very easily, we can password protect a directory (or multiple) of a web site which require a username and password to access. The login procedure for these secure directories is handled automatically by the web browser using a pop-up login interface (you've probably seen these before).

To begin, decide which directory you would like to password protect (note that all files and subdirectories within the directory will be password protected), then create a .htaccess file following the main instructions and guidance which includes the following text:

AuthName "Admin Area"
AuthUserFile /path/to/password/file/.htpasswd
AuthType Basic
require valid-user  

The password file would contain something similar to the following text:

username:encryptedpassword
daniel_mark:oCF9Pam/MXJg2 

You cannot just make up the password, on Unix/Linux servers they must be encrypted by the server, on Windows servers you do just use a plain text password as Windows does not offer any encryption methods.


Deny visitors by IP Address

One of the blocking features offered by Apache enabled us to deny access to some visitos by ip address. This is very usedful for blocking unwanted visitors or to only allow the website administrators access to a specific area of the website.

To start with, determine the folder to be protected, list the ip addresses to block and create the .htaccess file with the following text.

order allow,deny
deny from 192.168.25.10
deny from 52.31.20.75
allow from all

To set-up block for for all visitors except your ip address you can follow.

order allow,deny
allow from 192.168.25.10
deny from all

Where 192.168.25.10 is your ip address.


Hotlink Prevention

Hotlink prevention refers to stopping websites that otherwise not your own from displaying your files content from other websites. most common uses is displaying your copyrighted images to other websites which consumes your bandwidth, which cost money.

using .htaccess we can prevent other websites from hotlinking your content. This functionality however requires that 'mod_rewrite' is enabled on your server. Please check with your system administrator on how to enable this module.

To set-up a hotlink prevention for images and css files you will have to enter the text below:

RewriteEngine on
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^http://(www\.)?yourdomain.com/.*$ [NC]
RewriteRule \.(gif|jpg|css)$ - [F]

This means that all .gif, .jpg. and .css files from your domain yourdomain.com is protected from hotlinking.


Directory Index

the directory index command allows you to display the default page when a diretory is accessed. if a visitor requests a directory from your website for example '/this_folder/', it will display the default page index.html.

To set-up a directory index you just write the commands below:

DirectoryIndex index.html index.cgi index.php

This is the command for calling multiple files as a directory index for your website.


Change Server Signature

To change the server signature which is displayed as part of your apache error document you enter the commands:

ServerSignature EMail
SetEnv SERVER_ADMIN myname@thisemailofmine.com

this will change the email address.

To remove the server signature just copy:

ServerSignature Off

Prevent access to your PHP include files

If you have a directory containing PHP includes, that you do not wish to be accessed directly from the browser, there is a way of disabling the directory using Mod_Rewrite.

## Enable Mod Rewrite, this is only required once in each .htaccess file
RewriteEngine On 
RewriteBase / 
## Test for access to includes directory
RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /includes/ .*$ [NC] 
## Test that file requested has php extension 
RewriteCond %{REQUEST_FILENAME} ^.+\.php$ 
## Forbid Access 
RewriteRule .* - [F,NS,L]

Prevent Access to php.ini

If you run the risk of someone accessing your php.ini or php.cgi files directly through their browsers, you can limit access to them using .htaccess.

<FilesMatch "^php5?\.(ini|cgi)$">
Order Deny,Allow 
Deny from All 
Allow from env=REDIRECT_STATUS 
</FilesMatch>

Prevent access to .htaccess

Add the following code block to your htaccess file to add an extra layer of security. Any attempts to access the htaccess file will result in a 403 error message. Of course, your first layer of defense to protect htaccess files involves setting htaccess file permissions via CHMOD to 644:

# secure htaccess file
<Files .htaccess>
 order allow,deny
 deny from all
</Files>

Block Robots, Site Rippers and Offline Browsers

Eliminate some of the unwanted scum from your userspace by injecting this handy block of code. After such, any listed agents will be denied access and receive an error message instead. Please advise that there are much more comprehensive lists available this example has been truncated for business purposes. Note: DO NOT include the “[OR]” on the very last RewriteCond or your server will crash, delivering “500 Errors” to all page requests.

# deny access to evil robots site rippers offline browsers and other nasty scum
RewriteBase /
RewriteCond %{HTTP_USER_AGENT} ^Anarchie [OR]
RewriteCond %{HTTP_USER_AGENT} ^ASPSeek [OR]
RewriteCond %{HTTP_USER_AGENT} ^attach [OR]
RewriteCond %{HTTP_USER_AGENT} ^autoemailspider [OR]
RewriteCond %{HTTP_USER_AGENT} ^Xaldon\ WebSpider [OR]
RewriteCond %{HTTP_USER_AGENT} ^Xenu [OR]
RewriteCond %{HTTP_USER_AGENT} ^Zeus.*Webster [OR]
RewriteCond %{HTTP_USER_AGENT} ^Zeus
RewriteRule ^.* - [F,L]

Require SSL

To require the website to serve the page using SSL.

# require SSL
SSLOptions +StrictRequire
SSLRequireSSL
SSLRequire %{HTTP_HOST} eq "domain.tld"
ErrorDocument 403 https://domain.tld

# require SSL without mod_ssl
RewriteCond %{HTTPS} !=on [NC]
RewriteRule ^.*$ https://%{SERVER_NAME}%{REQUEST_URI} [R,L]

Force SSL

To force all web traffic to use HTTPS insert the following lines of code in the .htaccess file in your website’s root folder.

Important: If you have existing code in your .htaccess, add this above where there are already rules with a similar starting prefix.

RewriteEngine On 
RewriteCond %{SERVER_PORT} 80 
RewriteRule ^(.*)$ https://www.example.com/$1 [R,L]

Just replace www.example.com to your actual domain name.

To force a specific domain to use HTTPS, use the following lines of code in the .htaccess file in your website's root folder:

RewriteEngine On 
RewriteCond %{HTTP_HOST} ^example\.com [NC]
RewriteCond %{SERVER_PORT} 80 
RewriteRule ^(.*)$ https://www.example.com/$1 [R,L]

If you want to force SSL on a specific folder you can insert the code below into a .htaccess file placed in that specific folder:

RewriteEngine On 
RewriteCond %{SERVER_PORT} 80 
RewriteCond %{REQUEST_URI} folder 
RewriteRule ^(.*)$ https://www.example.com/folder/$1 [R,L]