11.12.07

"Various .htaccess samples and tutorials" - DreamHost Knowledge Base

.htaccess


Many people have only taken the .htaccess file as far as using it for password protection and custom error documents. There is a lot more to what can be done with an .htaccess than just these two features. The .htaccess file is a normal file that you can edit in programs such as Notepad, just as simple as editing your everyday documents.


.htaccess is not a name of a file; it's a file with a file extension, but no name. A file on Windows consists of a filename and an extension, such as document.doc. Windows doesn't allow files with an extension and no filename. However, on UNIX, you can call a file whatever you want, extension or no extension.


Warning


Although using .htaccess on your virtual server hosting account is extremely unlikely to cause you any problems (if something is wrong it simply won't work), you should be wary if you are using Microsoft FrontPage Extensions. The FrontPage extensions use the .htaccess file so you should not really edit it to add your own information. If you do want to (this is not recommended, but possible) you should download the .htaccess file from your server first (if it exists) and then add your code at the top of the file.


Creating the .htaccess File


To create a .htaccess file on Windows, just open a new document in Notepad and save it as .htaccess and make sure All files is selected in the Save as type drop-down menu so it doesn't save it as .htaccess.txt. When you go to upload an .htaccess file to your account, make sure that the data transfer mode is set to ASCII, never BINARY since it is a text file. While .htaccess files will work just by uploading them, we recommend that you CHMOD the .htaccess file to 644 (RW-R--R--). This makes the file readable by your web server, but at the same time, disables browsers from reading it. If your .htaccess file can be read by anyone, you're security is in big trouble.


When you create an .htaccess file, make sure that your text editor has word wrap disabled. If you don't, your text editor might add characters to the file that will cause problems with the Web server which will result in a non-functional .htaccess file and a 500 server error on your website's home page. Also make sure that all of your commands in an .htaccess file are on a separate line. If you don't you will end up with an .htaccess file that will cause problems on your account.


When you use a .htaccess file on your web server, the file affects the current directory and any of it's sub-directories. If you place an .htaccess file in the root directory of your website, it will affect every directory on your website.


Custom Error Pages


Custom error pages enable you to customize the pages that are displayed when an error occurs. Not only will they make your website seem a lot more professional, but they can also save you some visitors. If a visitor sees a generic error page, they are likely to leave your site. However, if they see a helpful error page, they might just stay at your site because they can just click on a link to go to another page within your site. You can create error pages for all error codes, however many webmasters only make error pages for the 4 most common errors, which are:



  • Error 401 - Authorization Required

  • Error 403 - Forbidden

  • Error 404 - Not Found

  • Error 500 - Internal Server Error


To specify what the server should do when an error is found on your website, enter the following into an .htaccess file:


ErrorDocument

/home/LOGIN/public_html/error-document.html

Change

to the code of the error. Also, change the path to the error document. Simply repeat the above line of code for all other errors. Once the file is uploaded, your visitors will be directed to the page that you specified.


Here's a sample .htaccess file with ErrorDocument enabled:


ErrorDocument 401 /401.html
ErrorDocument 403 /403.html
ErrorDocument 404 /404.html
ErrorDocument 500 /500.html

You can use full URL's for the path to your error documents on all error codes except 401, which must use a local path. Also, instead of specifying a URL for an error code, you can display a message too. Here's an example:


ErrorDocument 404 "

Sorry, the document you requested could not be found.


"

This is quite useful if you only need to display a short message because it saves you having to create additional files. As you can see, you can use normal HTML code.


Here's another .htaccess file with ErrorDocument enabled. This time, we are displaying messages instead of going to a different URL:


ErrorDocument 401 "

Error 401


Authorization Required.


"
ErrorDocument 403 "

Error 403


Forbidden.


"
ErrorDocument 404 "

Error 404


Not Found.


"
ErrorDocument 500 "

Error 500


Internal Server Error.


"

Limit the Number of Concurrent Visitors to your Website


If you need to limit the amount of concurrent visitors to your website, this can be easily set up. Open a program such as Notepad and insert the following line of code:


MaxClients


Change

to the maximum number of clients you want to allow access to your website.


Disable Directory Listings


Occasionally, you may not have a default index document in a directory. If a default document is not found, whenever a visitor types in the directory name in their browser, a full listing of all the files in that directory will be displayed. This could be a security risk for your site. To prevent without having to add a default index document to every folder, you can enter the following line in your .htaccess file to disable a directory's contents from being shown:


Options -Indexes

Deny/Allow Certain IP Addresses">Deny/Allow Certain IP Addresses


If you have problems with certain visitors to your website, you can easily ban them. There are two different ways to ban visitors. This can be done using their IP address or with the domain name which they came from.


Here's an example showing you how to deny a user by their IP address:


order allow,deny
deny from 201.68.101.5
allow from all

The above code will deny the 201.68.101.5 IP address and allow everyone else to enter. If you want to deny a block of IP addresses, use this code:


order allow,deny
deny from 201.68.101.
allow from all

The above code will deny the 201.68.101.0 IP address, the 201.68.101.5 IP address and all the way up to 201.68.101.255 or 255 IP addresses. Here's an example showing you how to deny a user by the domain name from which they came from:


order allow,deny
deny from www.theirdomain.com
allow from all

The above code will deny anyone coming from www.theirdomain.com and allow everyone else to enter. Here's an example showing you how to deny a user from a domain name and all subdomains within the domain name:


order allow,deny
deny from .theirdomain.com
allow from all

The above code will deny anyone coming from www.theirdomain.com, all sub-domains within the domain and allow everyone else to enter.


Order deny,allow
Deny from all
Allow from youripaddress

The above code will block all visitors from accessing your site except for yourself if you replace youripaddress with the IP address that was assigned to you by your ISP.


Deny Access To a Folder During a Specific Time


If for some reason you would like to block access to files in a directory during a specific time of day, you can do so by adding the following code to an .htaccess file.


RewriteEngine On
# If the hour is 16 (4 PM)
RewriteCond %{TIME_HOUR} ^16$
# Then deny all access
RewriteRule ^.*$ - [F,L]
# Multiple hour blocks
# If the hour is 4 PM or 5 PM or 8 AM
RewriteCond %{TIME_HOUR} ^16|17|08$

Alternative Index Files


When a visitor accesses your website, the server checks the folder for an index file. Some examples of common index files are: index.htm, index.html, index.php, index.cgi, index.pl. The supported index files depend on the how the server is set up. If the server cannot find an index file, it will try to display an index of all the files within the current directory, however if this is disabled, the server will end up displaying a 403 forbidden error. Using .htaccess, you can use a completely different index file instead of the defaults listed above. To do this, insert the following line into an .htaccess file:


DirectoryIndex pagename.html

Change pagename.html to the page that you would like to use as the index file.


Redirection


Using Redirect in an .htaccess file will enable you to redirect users from an old page to a new page without having to keep the old page. For example if you use index.html as your index file and one day rename index.html to home.html, you could set up a redirect to redirect users from index.html to home.html and index.html. Redirect works by typing:


Redirect /home/LOGIN/public_html/path/to/old/file/old.html http://www.yourdomain.com/new/file/new.html

The first path to the old file must be a local UNIX path. The second path to the new file can be a local UNIX path, but can also be a full URL to link to a page on a different server.


Here are a few examples of some redirects:


Redirect / /new/
Redirect /index.html /default.html
Redirect /private/ http://www.anotherdomain.com/private/
Redirect /img/logo.gif http://www.photos.net/images/logo.gif

Protect Your .htaccess File


When a visitor tries to obtain access to your .htaccess or .htpasswd file, the server automatically generates a 403 forbidden error, even with the file permissions at their default settings. However, you can apply a bit more security to your .htaccess files by adding the following code:



order allow,deny
deny from all


If you would like to redirect anything from http://domain.com to http://www.domain.com (so the www is always in the URL), you can accomplish this by using the code below. This is helpful in search engine optimization and will help give your site a higher page rank.


RewriteEngine On
RewriteCond %{HTTP_HOST} !^www\..* [NC]
RewriteRule ^(.*) http://www.%{HTTP_HOST}/$1 [R=301]

Prevent Image Hot Linking


Hot linking or bandwidth stealing is a common problem. It happens when people link to files and images on a different server, display them on their website and the bandwidth is at the other person's expense. By entering the lines below, you can prevent hot linking to your website:


RewriteEngine On
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^http://(www\.)?yourdomain.com/.*$ [NC]
RewriteRule \.(gif|jpg)$ http://www.yourdomain.com/hotlink.gif [R,L]

Change yourdomain.com to your domain name. On the last line of code, change hotlink.gif to the path to an image file that explains that hot linking is disabled on your server or display a spacer image.


Force Text Files to Download and Not Show in Your Browser


By default, if a text file (.txt) is requested, the contents of the file is shown in the browser and is not downloaded. This is because the default MIME type for .txt files specifies to show the files and not download them. You can however change this by adding the line below:


AddType application/octet-stream txt

Be warned though, every .txt file in the current directory and any subdirectories will be affected. If you only need to target a specific file, use this code:



AddType application/octet-stream txt

Email Address">Specify the Server Administrators Email Address


When users on your website encounter an error, a page is displayed with details about the error and the server administrator's email address is displayed. To modify the server administrator's email address insert the following code:


ServerAdmin admin@yourdomain.com

Be sure to change admin@yourdomain.com to the server administrator's email address.


Specify a Custom Error Log


The ErrorLog feature allows you to specify the local UNIX path to store your server error logs. These logs contain errors that visitors have encountered on your website. To specify a custom error log on your account, insert the following code:


ErrorLog /logs/error_log.log

You can change the path and filename of the error log, but your path must start with a forward slash.


Enable Password Protection


Password protection is probably the most popular feature of htaccess and is used all over the Internet. The reason why it is so popular is because it is very simple to set up and is the strongest form of protection which cannot be bypassed. When you set up password protection, you need to set up the password protection options in a .htaccess file and you need to set up usernames and passwords inside a .htpasswd file.


First, we are going to set up the usernames and passwords inside the .htpasswd file. The passwords inside a .htpasswd file are encrypted for added security, so you will need to use the htpasswd generator utility to create your usernames and passwords.


Once you have created the required usernames and passwords, you need to place them inside a .htpasswd file. Open a program such as Notepad and copy the username and password combinations that you generated using the htpasswd generator utility and place each username/password combination on it's own line. Here's a sample .htpasswd file with 3 username/password combinations specified:


user:XsexPxQgcBoTc
webmaster:LMmm0OcSGsnI2
admin:oZ8O/CyiGjtHE

Once your .htpasswd contains all of the username and passwords required, save the file as .htpasswd (be sure to select All files in the Save as type if you are using Notepad). Leave the file where it is for now, as we now need to set up the .htaccess file.


Setting up the .htaccess file is quite simple, all you need to do is specify the path to the .htpasswd file, the name of the restricted area, what user(s) to require and the authorization type.


The first thing to configure is the path to the .htpasswd file:


AuthUserFile /home/LOGIN/public_html/path/to/.htpasswd

Next up, what the restricted area is called.


AuthName Password Protected

Then, the authorization type:


AuthType basic

Finally, you need to specify what users are allowed to enter the restricted area. Even if you have for example 10 users in your .htpasswd file, you can allow only some users:


require user admin

Or, to allow all users that are listed in the .htpasswd file to access the restricted area:


require valid-user

Here's a sample .htaccess file setup for password protection. Copy the code below and change the path to the .htpasswd file, the name of the restricted area and what users to require. Leave the AuthType as it is:


AuthUserFile /pub/home/htdocs/.htpasswd
AuthName "Password Protected"
AuthType Basic
require valid-user

Open a program such as Notepad, insert the code, and save the file as .htaccess. Then upload .htpasswd and .htaccess to your account. Remember that you have to upload the .htpasswd to the directory specified in the AuthUserFile part of the .htaccess file. Also, remember that wherever you place the .htaccess file, that directory and any sub-directories will now be password protected. Attempt to access the protected directory and you will be prompted to enter a username and password.


The features that have been covered in this tutorial are the most commonly used features within a .htaccess file. There are many more different features that can be used. To learn more, check out Apache's website on Apache Directives.

No comments: