The Apache web server has a number of configuration options that are available to the server administrator. In a shared hosting environment, you don't have access to the main Apache configuration so you're stuck with the default configuration. However, it is possible to override some of the default settings by creating (or editing) a file named .htaccess. The .htaccess is a simple ASCII text file placed in your www directory or in a subdirectory of your www directory. You can create or edit this file in any text editor (such as NotePad) and then upload it to the directory for which you want to modify the settings. Be sure that the file is uploaded in ASCII (not BINARY) format, and be sure that the file permissions for the file are set to 644 (rw-r--r--). This allows the server to access the file, but prevents visitors from accessing the file through their web browser (a security risk.)
Commands in the .htaccess file affect the directory that it's placed in and all subdirectories. If you place the .htaccess file in your www directory, it will affect your entire web site. If you place it in a subdirectory of your www directory, it will affect only that directory plus and subdirectories of that directory.
Most .htaccess commands are designed to be placed on one line. If your text editor wraps lines automatically, you should disable that function before saving and uploading your file. Also, note that .htaccess commands are case-sensitive.
Please note that we do not technically support overriding the default server settings. The information presented here may work and it may not, or it may work today and not tomorrow. Use it at your own risk.
Some of the things you can do with .htaccess include:
Customize Error Messages
If you want to override the server's error pages, you can use .htaccess to define your own messages. This capability is discussed in the Custom Error Messages section of the manual. An example of the syntax is:
ErrorDocument 500 /error.html
Override SSI Settings
By default, only pages ending in the .shtml extension will parse server-side includes (SSI) on our servers. You can override this restriction in your .htaccess file:
If you want to override the default server configuration so that SSI will work with .html documents, you can create a file named .htaccess and upload it (in ASCII mode) to your main www directory. Add the following lines to your .htaccess file:
AddType text/html .html
AddHandler server-parsed .html
If you want both .html and .htm documents to parse SSI, create your .htaccess file with these lines:
AddType text/html .html
AddHandler server-parsed .html
AddHandler server-parsed .htm
Change Your Default Home Page
In order to browse your site by specifying the domain name only (e.g., http://www.hostingmanual.net) instead of having to specify an exact page filename (e.g., http://www.hostingmanual.net/filename.html), you must have an index page in your www directory. Default acceptable file names for index pages include index.htm,index.html,index.cgi,index.shtml, index.php, etc. Note that they're all named index.*.
There is also a default order of precedence for these names. So if you have both a file named index.cgi and a file named index.html in your directory, the server will display index.cgi because that name takes a higher precedence than index.html.
Using .htaccess, you can define additional index filenames and/or change the order of precedence. To define your index page as hieronymous.html add the following line to your .htaccess file:
DirectoryIndex hieronymous.html
This will cause the server to look for a file named hieronymous.html. If it finds that file, it will display it. If it does not find that file, it will return a 404 Missing Page error.
To change the order of precedence, enter a DirectoryIndex command with multiple file names on the same line. The order in which the file names are listed (from left to right) determines the order of precedence. For example,
DirectoryIndex hieronymous.html index.cgi index.php index.html
Enable Directory Browsing
Due to security concerns we have removed the default setting that allowed directory indexing. This is the option that allows the contents of a directory to be displayed in the browser when the directory does not contain an index page.
For example, if you make an http call to a directory such as http://yourdomain.com/images/, it would list all the images in that directory without the need for an html page with links.
If you require this option on specific directories it is still available. You can reactivate it by adding the following line to your .htaccess file:
Options +Indexes
Once this is added, the directory will fully index again.
Block Users from Accessing Your Web Site
If you want to deny access to a particular individual, and you know the IP address or domain name that the individual uses to connect to the Internet, you can use .htaccess to block that individual from your web site.
<Limit GET>
order deny,allow
deny from 123.456.789.000
deny from 456.78.90.
deny from .aol.com
allow from all
</Limit>
In the example above, a user from the exact IP number 123.456.789.000 would be blocked; all users within a range of IP numbers from 456.78.90.000 to 456.78.90.999 would be blocked; and all users connecting from America Online (aol.com) would be blocked. When they attempted to browse your web site, they would be presented with the 403 Forbidden ("You do not have permission to access this site") error.
Redirect Visitors to a New Page or Directory
Let's say you re-do your entire web site, renaming pages and directories. Visitors to the old pages will receive the 404 File Not Found error. You can solve this problem by redirecting calls to an old page to the new page. For example, if your old page was named oldpage.html and that page has been replaced by newpage.html, add this line to your .htaccess file:
Redirect permanent /oldpage.html http://www.mydomain.com/newpage.html
Of course, you want to replace mydomain.com with your actual domain name. Now, when the visitor types in http://www.mydomain.com/myoldpage.html, they will be automatically redirected to http://www.mydomain.com/mynewpage.html.
If you've renamed a directory, you can use one redirect line to affect all pages within the directory:
Redirect permanent /olddirectory http://www.mydomain.com/newdirectory/
Note that the old page or directory is specified using the system path relative to your www directory, while the new page or directory is specified by the absolute URL.
Prevent Hot Linking and Bandwidth Leeching
What if another web site owner is stealing your images and your bandwidth by linking directly to your image files from his/her web site? You can prevent this by adding this to your .htaccess file:
RewriteEngine on
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^http://(www\.)?mydomain.com/.*$ [NC]
RewriteRule \.(gif|jpg)$ - [F]
Replace mydomain.com with your actual domain name. With this code in place, your images will only display when the visitor is browsing http://mydomain.com. Images linked from other domains will appear as broken images.
If you're feeling particularly nasty, you can even provide an alternative image to display on the hot linked pages -- for example, an image that says "Stealing is Bad ... visit http://mydomain.com to see the real picture that belongs here." Use this code to accomplish that:
RewriteEngine on
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^http://(www\.)?mydomain.com/.*$ [NC]
RewriteRule \.(gif|jpg)$ http://www.mydomain.com/dontsteal.gif [R,L]
This time, replace mydomain.com with your domain name, and replace dontsteal.gif with the file name of the image you've created to discourage hot linking.
Prevent viewing of .htaccess or other files
To prevent visitors from seeing the contents of your .htaccess file, place the following code in the file:
<Files .htaccess>
order allow,deny
deny from all
</Files>
If you want to prevent visitors from seeing another file, just substitute that file's name for .htaccess in the Files specification.
FUN WITH .htaccess
The Apache web server has a number of configuration options that are available to the server administrator. In a shared hosting environment, you don't have access to the main Apache configuration so you're stuck with the default configuration. However, it is possible to override some of the default settings by creating (or editing) a file named .htaccess.
The .htaccess is a simple ASCII text file placed in your www directory or in a subdirectory of your www directory. You can create or edit this file in any text editor (such as NotePad) and then upload it to the directory for which you want to modify the settings. Be sure that the file is uploaded in ASCII (not BINARY) format, and be sure that the file permissions for the file are set to 644 (rw-r--r--). This allows the server to access the file, but prevents visitors from accessing the file through their web browser (a security risk.)
Commands in the .htaccess file affect the directory that it's placed in and all subdirectories. If you place the .htaccess file in your www directory, it will affect your entire web site. If you place it in a subdirectory of your www directory, it will affect only that directory plus and subdirectories of that directory.
Most .htaccess commands are designed to be placed on one line. If your text editor wraps lines automatically, you should disable that function before saving and uploading your file. Also, note that .htaccess commands are case-sensitive.
Please note that we do not technically support overriding the default server settings. The information presented here may work and it may not, or it may work today and not tomorrow. Use it at your own risk.
Some of the things you can do with .htaccess include:
Customize Error Messages
If you want to override the server's error pages, you can use .htaccess to define your own messages. This capability is discussed in the Custom Error Messages section of the manual. An example of the syntax is:
ErrorDocument 500 /error.html
Override SSI Settings
By default, only pages ending in the .shtml extension will parse server-side includes (SSI) on our servers. You can override this restriction in your .htaccess file:
If you want to override the default server configuration so that SSI will work with .html documents, you can create a file named .htaccess and upload it (in ASCII mode) to your main www directory. Add the following lines to your .htaccess file:
AddType text/html .html
AddHandler server-parsed .html
If you want both .html and .htm documents to parse SSI, create your .htaccess file with these lines:
AddType text/html .html
AddHandler server-parsed .html
AddHandler server-parsed .htm
Change Your Default Home Page
In order to browse your site by specifying the domain name only (e.g., http://www.hostingmanual.net) instead of having to specify an exact page filename (e.g., http://www.hostingmanual.net/filename.html), you must have an index page in your www directory. Default acceptable file names for index pages include index.htm,index.html,index.cgi,index.shtml, index.php, etc. Note that they're all named index.*.
There is also a default order of precedence for these names. So if you have both a file named index.cgi and a file named index.html in your directory, the server will display index.cgi because that name takes a higher precedence than index.html.
Using .htaccess, you can define additional index filenames and/or change the order of precedence. To define your index page as hieronymous.html add the following line to your .htaccess file:
DirectoryIndex hieronymous.html
This will cause the server to look for a file named hieronymous.html. If it finds that file, it will display it. If it does not find that file, it will return a 404 Missing Page error.
To change the order of precedence, enter a DirectoryIndex command with multiple file names on the same line. The order in which the file names are listed (from left to right) determines the order of precedence. For example,
DirectoryIndex hieronymous.html index.cgi index.php index.html
Enable Directory Browsing
Due to security concerns we have removed the default setting that allowed directory indexing. This is the option that allows the contents of a directory to be displayed in the browser when the directory does not contain an index page.
For example, if you make an http call to a directory such as http://yourdomain.com/images/, it would list all the images in that directory without the need for an html page with links.
If you require this option on specific directories it is still available. You can reactivate it by adding the following line to your .htaccess file:
Options +Indexes
Once this is added, the directory will fully index again.
Block Users from Accessing Your Web Site
If you want to deny access to a particular individual, and you know the IP address or domain name that the individual uses to connect to the Internet, you can use .htaccess to block that individual from your web site.
<Limit GET>
order deny,allow
deny from 123.456.789.000
deny from 456.78.90.
deny from .aol.com
allow from all
</Limit>
In the example above, a user from the exact IP number 123.456.789.000 would be blocked; all users within a range of IP numbers from 456.78.90.000 to 456.78.90.999 would be blocked; and all users connecting from America Online (aol.com) would be blocked. When they attempted to browse your web site, they would be presented with the 403 Forbidden ("You do not have permission to access this site") error.
Redirect Visitors to a New Page or Directory
Let's say you re-do your entire web site, renaming pages and directories. Visitors to the old pages will receive the 404 File Not Found error. You can solve this problem by redirecting calls to an old page to the new page. For example, if your old page was named oldpage.html and that page has been replaced by newpage.html, add this line to your .htaccess file:
Redirect permanent /oldpage.html http://www.mydomain.com/newpage.html
Of course, you want to replace mydomain.com with your actual domain name. Now, when the visitor types in http://www.mydomain.com/myoldpage.html, they will be automatically redirected to http://www.mydomain.com/mynewpage.html.
If you've renamed a directory, you can use one redirect line to affect all pages within the directory:
Redirect permanent /olddirectory http://www.mydomain.com/newdirectory/
Note that the old page or directory is specified using the system path relative to your www directory, while the new page or directory is specified by the absolute URL.
Prevent Hot Linking and Bandwidth Leeching
What if another web site owner is stealing your images and your bandwidth by linking directly to your image files from his/her web site? You can prevent this by adding this to your .htaccess file:
RewriteEngine on
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^http://(www\.)?mydomain.com/.*$ [NC]
RewriteRule \.(gif|jpg)$ - [F]
Replace mydomain.com with your actual domain name. With this code in place, your images will only display when the visitor is browsing http://mydomain.com. Images linked from other domains will appear as broken images.
If you're feeling particularly nasty, you can even provide an alternative image to display on the hot linked pages -- for example, an image that says "Stealing is Bad ... visit http://mydomain.com to see the real picture that belongs here." Use this code to accomplish that:
RewriteEngine on
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^http://(www\.)?mydomain.com/.*$ [NC]
RewriteRule \.(gif|jpg)$ http://www.mydomain.com/dontsteal.gif [R,L]
This time, replace mydomain.com with your domain name, and replace dontsteal.gif with the file name of the image you've created to discourage hot linking.
Prevent viewing of .htaccess or other files
To prevent visitors from seeing the contents of your .htaccess file, place the following code in the file:
<Files .htaccess>
order allow,deny
deny from all
</Files>
If you want to prevent visitors from seeing another file, just substitute that file's name for .htaccess in the Files specification.
Eliminate Code Red and NIMDA Virus Attacks from your Access Log
The following suggestion was provided by a customer:
For the last few months my logs have been filling up with Nimda and Code Red failed attacks ... placing the below redirects in my .htacess appears to have eliminated the logging problem without affecting my personalized error redirecting scripts. I just thought others may find this handy.
redirect /scripts http://www.stoptheviruscold.invalid
redirect /MSADC http://www.stoptheviruscold.invalid
redirect /c http://www.stoptheviruscold.invalid
redirect /d http://www.stoptheviruscold.invalid
redirect /_mem_bin http://stoptheviruscold.invalid
redirect /msadc http://stoptheviruscold.invalid
RedirectMatch (.*)\cmd.exe$ http://stoptheviruscold.invalid$1
We haven't tried it, but it seems like a nifty idea. If you're tired of seeing those calls cluttering up your statistics, it might be worth a try. Thanks Roy!
Using the .htaccess File
Collated by Miraz Jordan
Web designers often ask how to handle redirects or to password protect directories. The .htaccess file can do these things and more. For this article Miraz Jordan has collated various tips mentioned on the Wisewomen mailing list, and from several other sources.
What the .htaccess file can do
- If you're reorganising your site and moving pages around, you can use the .htaccess file to redirect visitors from the old page to the new one.
- Another function of the .htaccess file is to allow you to serve up pages which include PHP or Server Side Includes (SSI) but whose file name still uses the .htm or .html extension.
- Allow or prevent directory browsing.
- Because the server should check the .htaccess file before anything is delivered to the client, you can use it to password protect parts of your site.
- You can also block various bots with the .htaccess file — for example, you can keep some spammers out, or prevent search engine spiders from indexing your images folder.
You can read the definitive information on .htaccess files at Apache.org.
Reveal hidden .htaccess files
The filename for the .htaccess file begins with a . (dot). This causes it to be hidden on many Operating Systems. You may have trouble finding or working with such hidden files.
On the server
Set your FTP software to show files beginning with a dot, or access the file through your server's Control Panel — File Manager.
Some FTP software, such as Interarchy, allow you to edit files directly on the server. Select a file and choose Listing menu — Edit with. To get Interarchy to display files whose name begins with a dot visit Preferences — transfers and uncheck Ignore .files.
On Mac OS X
If you download the file to a Mac running OS X you will have trouble finding it as the Mac hides files whose filenames begin with a dot. You can edit hidden files on a Mac though, provided you can find them.
A standard Finder search can find hidden files but you may find a tool such as Tinkertool or Pathfinder useful. Set the preferences to show hidden files. Be careful not to move, delete or edit any other hidden files unless you know what you're doing as otherwise you can break things.
On Windows
[Thanks to Susan from the WW list for this information and screen shot.]
If you download the file to a computer running Windows you will have trouble finding it as Windows hides files whose filenames begin with a dot. You can edit hidden files on Windows though, provided you can find them.
- Open File Explorer
- Go to Tools — Folder Options… and click on the tab "View".
- Make sure that the option "Show hidden files and folder" is checked.
Be careful not to move, delete or edit any other hidden files unless you know what you're doing as otherwise you can break things.
Create a new .htaccess file
Use a plain text editor such as Notepad (not Word) or TextEdit to create a document called htaccess.txt on your computer. Don't add the dot at the start of the filename or it may become invisible. Upload that file to your server, then rename it to .htaccess. Make sure you add the . (dot) at the start of the file name and remove the .txt extension. Be sure to upload it in ASCII format, not Binary.
FTP software such as Interarchy may allow you to directly create a new file on the Server. See the Listing menu — Create File.
The .htaccess file can go in the root directory and it will then also affect all directories below it. Each other directory may also have its own .htaccess file.
Redirects
Let's say you've moved a file or directory, or both: www.example.com/training/test.html is now located at www.example.com/learning/newtest.html. You want visitors to end up at the correct page, even if they use the old address.
Open the .htaccess file and enter this on one single line:
redirectpermanent /training/test.html http://www.example.com/learning/newtest.html
Note that this is search engine-friendly, too. Search engines will change the links in their index to the new link on the basis of the redirectpermanent directive. More info: httpd.apache.org/docs/mod/mod_alias.html#redirectperm.
Parse PHP in .html files
Perhaps you have have been learning PHP and want to include some commands in existing html files. The books will tell you to rename those files with a .php extension. Rather than renaming all your files you can use the .htaccess file to tell the server to allow html files to include php. More info: www.desilva.biz/php/phpinhtml.html.
Allow SSI in .html files
Tip provided by Deb from the WW list and rewritten by Miraz.
You may be on a server that requires files to end in .shtml for Server Side Includes. Here is a tip if you do not wish to use the .shtml extension, or if you have added Server Side Includes to existing .htm or .html files. Add the following to your .htaccess file:
AddType text/html .shtml .shtm .htm .html
AddHandler server-parsed .shtml .shtm .htm .html
You can add whichever extensions are relevant.
Files which must be parsed by the server before being displayed may not load as quickly as standard pages. If you use this code in your.htaccess file, the server will parse all .html and .htm pages, including those that do not contain any SSI includes. This could significantly slow the loading of pages which do not use the includes. Be cautious if your pages hold extensive graphics. [Deb mentioned she had not seen slower load times.]
Allow or prevent directory browsing
Tip provided by Deb and rewritten by Miraz.
A good way to increase security on your site involves the .htaccess file. You can override server settings to allow or prevent directory listing.
Prevent directory browsing
Suppose you have a directory which doesn't have a default file (index.html), such as a folder of images, for example. A visitor may enter an address ending with a / and see a list of all the files in the directory.
You can prevent directory browsing by adding this line to your .htaccess file:
IndexIgnore */*
Allow directory browsing
There may be times when you want or need to allow visitors to browse a directory. For example, you may need to allow access to files in a directory for downloading purposes on a server that is configured to not allow it.
Many servers are configured so that visitors cannot browse directories. In that case visitors will not see the contents of the directory but will instead get an error message.
You can override the servers settings and allow directory browsing with this line:
Options +Indexes
Password protection
Tip provided by Sheila from the WW list and rewritten by Miraz.
You can password protect individual files with .htaccess. It's usually done directory-wide with <Directory> but you can use <Files> to specify a single file:
<Files secret_file.html>
AuthType Basic
AuthName "Team Page"
AuthUserFile path_to_password_file
Require user username
</Files>This only protects the single page; all the files that it is linked to are not protected. More detailed information: httpd.apache.org/docs-2.0/howto/auth.html.
Block various bots
[Stephanie of Glenfinnan Web Hosting supplied this information which was rewritten and amplified by Miraz with reference to: www.webmasterworld.com/forum13/687.htm. Stephanie said: You can block various bots with the .htaccess file, Gini and someone else [from the WiseWomen list] posted their list of spam and spider bots [6 Kb txt file] awhile back
.]
Spambots frequently visit our sites for various nefarious purposes. You can block them like this:
RewriteEngine on
RewriteCond %{HTTP_USER_AGENT} ^.*Ants.*$ [OR]
RewriteCond %{HTTP_USER_AGENT} ^.*attach.*$ [OR]
[Many more similar lines …]
RewriteCond %{HTTP_USER_AGENT} ^.*Widow.*$ [OR]
RewriteRule /* http://www.fbi.gov [L,R]
The last line sends them off to the FBI, but you could use any URL you wish. Alternatively you could just send them to a standard error page:
RewriteRule ^.* - [F]
Summary
The .htaccess file is a very powerful file which can keep visitors away or send them elsewhere, protect pages and directories with a password, allow you to include PHP and SSI within pages which have a .html extension and prevent or allow directory browsing. Handle the .htaccess file with care but use this information as a starting point for further exploration.
Be sure to always test your site after making changes to the .htaccess file, and have fun experimenting.