Welcome, Guest. [ Log In ]
Question   Various .htaccess samples and tutorials
Search KBase


Top 5 in this Area:
1. How do I use .htaccess files?
2. How can I turn off the default directory listing in a directory?
3. How do I block people coming from a certain website or URL from visiting my site or directory?
4. Can I use .htaccess files?
5. Various .htaccess samples and tutorials

 
Various .htaccess samples and tutorials

.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 <ErrorCode> /home/LOGIN/public_html/error-document.html

Change <ErrorCode> 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 "<p><strong>Sorry, the document you requested could not be found.</strong></p>"

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 "<p>Error 401</p><p>Authorization Required.</p>"
ErrorDocument 403 "<p>Error 403</p><p>Forbidden.</p>"
ErrorDocument 404 "<p>Error 404</p><p>Not Found.</p>"
ErrorDocument 500 "<p>Error 500</p><p>Internal Server Error.</p>"

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 <Number of max clients>

Change <Number of max clients> 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

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:

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

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:

<Files yourfile.txt>
AddType application/octet-stream txt
</Files>

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.

Last updated: Nov 23, 2005.

Official Reply (2005-03-04 16:45:56 )
http://customersupport.websiteproviders.net/tutorials/htaccess/

is the source of this file
User Post (2006-01-10 16:34:44 by kgs)
Hmmmm. I have this in my .htaccess file (in the testblog directory): Redirect /home/kgs/freerangelibrarian.com/testblog/foo.html http://freerangelibrarian.com/testblog/bar.html ... yet alas it doesn't work.
User Post (2005-12-26 15:46:40 by pixel23)
For anyone else trying to figure out how to view the .htaccess files with CuteFTP, these directions from http://www.automateyourbusiness.com/forum/index.php?s=3d361c267537631cbbb161947b 48611d&showtopic=15&pid=36&st=0&#entry36
helped:

The .htaccess files (plus other files that begin with a dot) are special files that affect the fundamental operation of your website. As such, most FTP software will hide them so that you can't accidentally mess with them.

And as the file's not visible, if you encounter any problems, you're never quite sure whether the file did actually get to your site in one piece.

So, seeing as Cute FTP seems to be quite common, here's a quick tutorial on how to make .htaccess files visible:

- Make sure you're not connected to the site you're working on

- Go to the site manager, and right-click on the site in the listing .

- Pick "Properties"

- Click on the "Actions" tab

- Press the button called "Filter..."

- Check the option "Enable server-side filtering", and in the "Remote filter" box, enter "-a" (without the quotes)

- Keep pressing OK till you get back to the main screen.

- Connect to the site - you'll then see the .htaccess file if it transferred correctly.
User Post (2005-12-09 08:28:57 by mshensley)
Thanks, for the tip about the redirect url's. If the destination is not a fully qualified url, you will get a 500 error.
User Post (2005-11-10 21:38:55 by aosvath)
dpmsystems - Use a better FTP client, or unblock those files from not being shown.
User Post (2005-11-01 09:52:08 by billium)
You can also use the .htaccess file to run .html pages as php, therefore avoiding the .php extension. just put this in it:

<IfModule mod_php4.c>
AddType application/x-httpd-php .html
</IfModule>
User Post (2005-10-16 13:54:26 by foryouview)
martialarm (or anyone with a similiar question): You are looking for either the alias or mod_rewrite; check http://httpd.apache.org/docs/1.3/mod/directives.html
User Post (2005-10-14 02:32:15 by walterhutchens)
This is a GREAT, clear guide, usable by even command-line phobics like me. I had a WordPress blog directory that gave a 404 error everytime when I had .htaccess password protection on (which I first enabled through the dreamhost web interface). Not sure why---it worked fine with this blog for a while, and works fine with other sites, but somehow this one got messed up. I tried removing then recreating the htaccess passord protection through the dreamhost interface, but that didn't work. I (nervously) deleted the .htaccess and .htpasswd files through my ftp interface, then recreating them through dreamhost's interface--that didn't work, either. Then I found this guide and follwed it carefully, creating the .htaccess and htpasswd files from scracht--presto! Block back and IS password protected. Hooray. And thanks for this good, clear guide.
User Post (2005-09-27 12:06:56 by chargers)
dpmsystems: why not just SSH to your shell acount and delete the .htaccess file? Use 'ls -a' to show hidden files.
User Post (2005-09-13 16:34:41 by dpmsystems)
I've found out the hard way that once you upload an .htaccess file, it will never show in your directory listing with an FTP client. Which means that they only way to delete the file (or the directory that contains the errent .htaccess file) is to contact Dreamhost support and ask them to delete it for you. Which they always do ASAP :)
User Post (2005-07-16 01:14:27 by martialarm)
Errordocument 404 http://www.yoursite.com
RedirectMatch 301 (.*)\.html$ http://www.yoursite.com$1.phtml
RedirectMatch 301 (.*)\.asp$ http://www.yoursite$1.phtml

I am trying to use redirect and cover errors too.

on my old site I had .html and .asp files and want to be able to transfer to my new .phtml pages that match eg If people go to /file/file.html they will transfer to /file/file.phtml

BUT this has a negative effect - when people type http://www.yoursite.com they get the 301 redirect to http://www.yoursite.com/index.phtml

I would like to be able to keep http://www.yoursite.com and have engines and people go to http://www.yoursite.com without any index.phtml

How can I do this?
User Post (2005-05-04 13:26:53 by gpinto)
For the "Redirection" section: If you are using .htaccess to redirect from a document on you site to another, the destination must be a fully qualified URL.

Example:

Redirect /index.html http://yourdomain.com/another_dir/default.html