Tutorials Books Videos Forums

Change the theme! Search!
Rambo ftw!

Customize Theme


Color

Background


Done

Common .htaccess Tricks

by kirupa   |   17 March 2004 (Updated 7 December 2011)

  Have questions? Discuss this HTML tutorial with others on the forums.

A really cool technique that many web designers overlook is the use of the .htaccess file. Whenever you see a custom error page (404, 403, etc.), use server side includes, restrict IPs, load a default page, or do any host of events invisible to the user, somebody is taking advantage of what a .htaccess file has to offer.

What is a .htaccess File?

An .htaccess file is a simple configuration file that allows web servers like Apache to do some special things when serving HTML pages. This ".htaccess file" is a plain-text file that you save as .htaccess without any extra characters before or after the name of the file. I know the file's name is a little strange but, then again, most cool things' names are!

Here is how the file looks when uploaded to a web server:

[ notice the strange file naming convention ]

I've been using an .htaccess file for many years to handle all kinds of cool tricks on the server that you probably never see. In this article, you will see those tricks and hopefully find them useful in your own sites.

Note - Applying .htaccess to Folders and Sub-Folders
Your .htaccess file doesn't need to be in the root directory of your web server. You can put it in any directory, and the settings specified by that .htaccess file applies to the current directory as well as any subdirectories. This allows you to specify custom settings on a per directory basis if you really want it.

Editing a .htaccess File

If you don't already have a .htaccess file setup, simply copy and paste the line(s) of code that you will see shortly into Notepad, save the file as .htaccess, and upload the file to the root directory of your web server.

Use a Dedicated FTP Editor

Note that IDEs like Dreamweaver and Expression Web may not show the .htaccess file at the root of your server. Use a more advanced FTP tool like FileZilla or SmartFTP to see the .htaccess file.

In the next many sections, you'll learn common .htaccess tricks and the lines of text you need to add to take advantage of them.

1. Custom Error Pages

Don't you hate it when people access your site via a bad link and are faced with a boring error message such as "Permission Denied" or "Page Cannot be Found"? Well, you can liven up the error messages by creating custom error pages for each type of error you anticipate your visitors will encounter:

ErrorDocument 404 http://www.kirupa.com/404.htm
ErrorDocument 401 /admin/authorization.htm
ErrorDocument 403 /password/forbidden.htm

To create custom error pages, replace the error code next to ErrorDocument to the appropriate error code, and change the URL of the page that will receiving the error-prone user! For example, here is this site's 404 error page.

2. Redirects

Here is a nightmare scenario. You decide to shift an entire folder's worth of pages and images into a new folder on your server. If you aren't using any 3rd party programs to update any links to the new location, your users are going to be seeing a lot of the custom error pages.

Thanks to .htaccess, you can setup a redirect to transparently handle take people from the old location to the new location. For example, if you are interested in redirecting users from a folder called temp to another folder called developer, you would use the following code:

Redirect /temp //www.kirupa.com/developer

The first argument to the Redirect statement the folder or filename that you are trying to redirect people from. The second argument is the file or directory you are trying to get people to go to instead:

Redirect old file/folder new file/folder

The above line of code is a template for how the redirect feature of .htaccess works. Modify it as needed for your own needs.

3. Changing Home Page/Directory Page

When somebody types the URL to your site, more than likely, the index.htm or similar page like default.html will load first. The file that gets loaded as your default page is something you can change using the DirectoryIndex setting:

DirectoryIndex file.htm

With the above setting, users will load file.htm by default when they visit your site. For your cases, replace file.htm with the name of your default page. This will ensure that the page you specified gets loaded when a user types in the URL to your site.

4. IP Blocking

Dealing with troublemakers is a full-time job! A quick way of temporarily stopping people from accessing your site is to block them by IP.

To block people/computers with certain IPs from accessing your site, you can use the following command format:

order allow,deny
deny from 18.52.3.5
deny from 18.132.152
deny from 24.2
allow from all 

Of course, you would probably not be interested in blocking the fictitious IPs I mentioned above. You should change those to something more relevant. If you are really not well liked, you can add as many deny from lines of code as you want.

If somebody from an entire IP range is bugging you, you can block all IPs within that range by only entering a smaller portion of their IP such as 24.2. All IPs that begin with 24.2 such as 24.2.35.3 and 24.2.142.122 will also be blocked automatically.

5. Allowing Only a Certain IPs

Access you taketh, you can certainly grant...eth In the previous section, you learned how to ban an IP or range of IPs from accessing your site. If you want to only allow a certain IP range to access your site, you can use allow from lines:

order allow,deny
allow from 123.456.789.012
deny from all

I am generally not a fan of allowing based on IP, for you never know when your IP address may change. If you do control the IP address such as on your own private network or intranet, go all out with this setting if you don't have a better way of restricting access.

6. Turning On Compression (aka Reducing Your File Size!)

Did you know that you could potentially reduce the file size of your served content by over 70%? I am not kidding. If your server has the appropriate compression modules installed (mod_deflate or mod_gzip), you can decrease the file size of your pages by over 70% by just adding a single line to your .htaccess file:

SetOutputFilter DEFLATE

Once you've added this line, your server will compress all content that it sends to your browser.

You can test the benefits out for yourself with the following online tool. If you don't have a URL you can try, simply use this site's URL instead. I have compression enabled to reduce the amount of data you have to download:

htaccess results

[ yes, you save around 77% in bandwidth! ]

As you can see, the benefits are simply too good to pass up, so turn them on if you can.

7. Adding or Not Adding WWW to your URLs

There is a lot of debate on whether you need to have www as part of your URL. I side on wanting it, but you may strongly differ. Regardless of what your view is, you don't want to allow both http://mysite.com and http://www.mysite.com. Search engines don't like that.

By using a few lines of REGEX, you can redirect the URL a user is visiting to either use www or not use the www.

To always display the www, add the following to your htaccess file:

RewriteEngine on
RewriteBase /
RewriteCond %{HTTP_HOST} ^yoursite.com$
RewriteRule ^(.*) http://www.yoursite.com/$1 [R=301]

To never display the www, add the following lines:

RewriteEngine on
RewriteBase /
RewriteCond %{HTTP_HOST} ^www.yoursite.com$ [NC]
RewriteRule (.*) http://yoursite.com/$1 [R=301,L]

Simply replace yoursite.com with your domain...unless your web site is yoursite.com. In that case, you don't have to do anything!

Conclusion

The above .htaccess tricks are ones that I feel you will enjoy using because I've find them extremely useful. Remember, some server hosts may consider using or modifying a .htaccess file a violation of your privileges. Some HTML editing programs may have their own file management and access systems that do not play well when in the presence of .htaccess. Also, IIS servers do not support .htaccess files.

Thanks to njs12345 for providing some additional .htaccess insights with regards to sub-folders/folders and IIS servers.

Just a final word before we wrap up. If you have a question and/or want to be part of a friendly, collaborative community of over 220k other developers like yourself, post on the forums for a quick response!

Kirupa's signature!

The KIRUPA Newsletter

Thought provoking content that lives at the intersection of design 🎨, development 🤖, and business 💰 - delivered weekly to over a bazillion subscribers!

SUBSCRIBE NOW

Creating engaging and entertaining content for designers and developers since 1998.

Follow:

Popular

Loose Ends

:: Copyright KIRUPA 2024 //--