16 Useful .htaccess Tricks and Hacks For Web Developers

The .htaccess files (Hypertext Access file) is a very powerful configuration tool on Apache web server. The Apache web server has a number of configuration options that are available to the server administrator. The .htaccess is a simple ASCII text file placed in your website root directory. You can create and edit an .htaccess file using a text editor like notepad.

Here in this blog post I have come up with useful 16 tips and hacks to configure your web server.
As a configuration file .htaccess if a very powerful and a slight syntax error can result in a severe malfunction of your server. So to avoid that always try to keep a backup copies of all your files from the server before working with the .htaccess file.

1. Creating a custom error page with .htaccess on a linux apache is a very simple task. Using you a text editor like notepad you create an .htaccess files. Custom error pages give your website an professional look and catch those visitors who reach your website following a back link.

ErrorDocument 401 /error/401.php
ErrorDocument 403 /error/403.php
ErrorDocument 404 /error/404.php
ErrorDocument 500 /error/500.php

2. How to set the timezone on your server

SetEnv TZ America/Houston

3. Block IPs Using htaccess
Sometime you need to block certain IPs from accessing your entire site or directory. Its pretty simple task. All you have to do is inside the .htaccess file is put the following code.

allow from all
deny from
deny from 124.15

If you use the whole IP or a part of the IP to block and add the new ones in a new line.
When someone trying to access your site from the banned ip they will get a 403 error access forbidden message.

4. SEO Friendly 301 permanent redirects for bad/old links and moved links

Redirect 301 /d/file.html http://www.htaccesselite.com/r/file.html

5. Set the Email Address for the Server Administrator – Using this code you can specifying the default email address for the server administrator.

ServerSignature EMail
SetEnv SERVER_ADMIN default@domain.com

6. Hotlinking protection with .htaccess is very important because anyone can hot link to your images and eat up all your bandwith of your server. The following code will help you to prevent that.

Options +FollowSymlinks
# Protect Hotlinking
RewriteEngine On
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^http://(www.)?domainname.com/ [nc]
RewriteRule .*.(gif|jpg|png)$ http://domainname.com/img/hotlink_f_o.png [nc]

7. Block all requests from user agent – by creating a perfect .htaccess ban list, you can block all of unwanted user agents that will keep your server load down. Also Check out this interesting thread on webmaster world about the  228 user agents ban list.

## .htaccess Code :: BEGIN
## Block Bad Bots by user-Agent
SetEnvIfNoCase user-Agent ^FrontPage [NC,OR]
SetEnvIfNoCase user-Agent ^Java.* [NC,OR]
SetEnvIfNoCase user-Agent ^Microsoft.URL [NC,OR]
SetEnvIfNoCase user-Agent ^MSFrontPage [NC,OR]
SetEnvIfNoCase user-Agent ^Offline.Explorer [NC,OR]
SetEnvIfNoCase user-Agent ^[Ww]eb[Bb]andit [NC,OR]
SetEnvIfNoCase user-Agent ^Zeus [NC]
Order Allow,Deny
Allow from all
Deny from env=bad_bot
## .htaccess Code :: END

8. Redirect everyone to different site except few IP
-If you want to redirect all the visitors to a different IP. Also give access to certain  few IPs. You can use the code below

ErrorDocument 403 http://www.youdomain.com
Order deny,allow
Deny from all
Allow from
Allow from

9. Don’t want to display download request – Usually when you try to download something from a web server you get a request asking whether you want to save the file or open it.
To avoid that you can use the below code on your .htaccess file.

AddType application/octet-stream .pdf
AddType application/octet-stream .zip
AddType application/octet-stream .mov

10. Change the file type – Make any file be a certain kind of file type Makes image.jpg, index.html, default.cgi all act as php

<Files test>
ForceType application/x-httpd-php
SetHandler application/x-httpd-php

11. Block access to your .htaccess file – By adding he following code to your htaccess file will prevent attempts to access your htaccess file. This extra layer of security protects your htaccess file by displaying a 403 error message on the browser.

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

12. Protect access to certain specific file on your server – this can be done by adding the below mentioned code. For example you want to block with the file name default.jpg This will prevent the viewing of this file.

# prevent access of a certain file
<files default.jpg>
 order allow,deny
 deny from all

13. Prevent access to unauthorized browsing – Protecting specific directory browsing can be done by intructing the server to serve a Forbidden and Authorization required message while anyone requests to view that particular directory. Usually if you site doesn’t have a default index page any files within that directory is accessible to the visitors. To avoid that use the following code in the .htaccess file.

# disable directory browsing
Options All -Indexes

14. Setting the default page
– You can set the default page of a directory to any page you like. For example in this code the default page is set as about.html instead of index.html

# serve alternate default index page
DirectoryIndex about.html

15. Password protect your directories and files
– You can create authentication for certain files and directories from being access. The code has examples of both password protection for a single file and password protection for a entire directory.

# to protect a file
<Files secure.php>
AuthType Basic
AuthName “Prompt”
AuthUserFile /home/path/.htpasswd
Require valid-user

# password-protect a directory
AuthType basic
AuthName “This directory is protected”
AuthUserFile /home/path/.htpasswd
AuthGroupFile /dev/null
Require valid-user

16. Redirect an old domain to a new domain
– Using htaccess file you can redirect a old domain name to a new domain by adding the following code into the htaccess file. Basically what it does is it will remap the old domain to the new one.

# redirect from old domain to new domain
RewriteEngine On
RewriteRule ^(.*)$ http://www.yourdomain.com/$1 [R=301,L]

As htaccess files are very powerful, even a slightest syntax error can cause sever malfunction of your server. So it is crucial to take the backup copies of everything before you try the hacks and tricks on your hypertext access files. Post your thoughts with a comment.


  1. says

    Great list there listing the use of .htaccess. I know this may be out of this article’s subject but it would be excellent if you can post some more examples of URL rewrite especially with regards to SEO.

  2. Max says

    Thank you for posting this. I have one question regarding the use of an .htaccess file properly. Perhaps you can direct me to the correct solution.

    I have developed a new site for my domain, which sits under
    Is there any way to serve all requests from the root of the URL from the /new directory.
    For instance, if the user types in,
    the actual file sits at the
    link but I would like to remove the ‘new’ part from the URL.
    I have tried several .htaccess tricks but I always get a syntax error.

  3. andrew says

    While this is nice .htaccess is not a good way to do this. Its very inefficient and needs to be checked on each directory in the hierarchy. I would not advocate using this.

  4. says

    You should avoid that method for preventing hotlinking if you have any RSS feeds that contain images. You definitely don’t want to treat some of your most valuable readers like bandwidth thieves!

  5. says

    Hi guys,

    I tried to put in no. 7, which is “Block all requests from user agent” but got the following error :

    order not allowed here

    Appreciate anyone could help here. Thanks !


  6. reallife says

    A while back I had an interesting problem on my website. I had a domain where i needed to password protect /var/www/secret-site/ but on the other domain i needed /var/www/secret-site/awesome-stuff/ to be accessible without having to authenticate, I tried and failed, after a few minutes of searching I found out that “Satisfy Any” would solve this problem, it’s not a perfect method, but it works.

  7. says

    This is a very good article.

    I agree with you when it comes to blocking those sites that spam us.scape our posts, etc.

    It use to freak me out until my fiance explained we could block them.

  8. says

    1. Custom error pages are a very good idea. Make sure they are larger than 500 or so bytes because Internet Explorer will ignore any error page smaller than this and display its own.

    3. Make sure you use the start and end characters for IP address matching like this: ^$. If you don’t, the regex will match any part of the IP address. The regex will match (and block) the IP addresses,,,,,… etc…
    The short regex you have “124.15” will match (and block) as well as and If you only want to block IP addresses STARTING WITH 124.15 then you must make the regex ^124.15.

    6. You must be very careful when attempting to stop hotlinking. Most hotlinking strategies that use Apache rewrites end up with a large number of false positives. I’m not aware of any RSS readers or email clients sending referrers but web-based clients such as Google reader and Gmail will send referrers and hence will be blocked from loading images from your site.

    Also, if someone simply links to an image on your site (as opposed to embedding an image from your site in their site) then any users who click on that link will be treated as “bandwidth thieves” and will not get the image. This highlights the main problem with hotlink protection: you are punishing your visitors for the transgressions of their favourite blogger. At the very most you should only ever rewrite the image URL to a watermarked version of the same image (you can have PHP automatically watermark images for you on request) so that you can limit the damage caused by false positives.

    Any user who gets bitten too often by over-enthusiastic hotlink protection will end up installing a plugin to modify the referrer field to always be blank.

    7. The [NC] modifier at the end of the rewrite rule means [No Case]. This means that you don’t need to specify [Ww] and [Bb] to block WebBandit because ALL combinations of upper and lower case letters will already be matched.

    8. This is not a redirect. This is a 403 Forbidden HTTP status code response that specifies that the error page should be retrieved from another site. Although it results in the user seeing the other site, it is not the correct way to redirect a user.
    To conditionally redirect users based on IP address you should use RewriteCond. RewriteConds are very powerful and any tutorial about apache configuration files would be inadequate if it were missing them.

    RewriteCond %{REMOTE_ADDR} !^$
    RewriteCond %{REMOTE_ADDR} !^$
    RewriteRule .* http://www.yourdomain.com [R=301,L]

    11. Access to .htaccess files are blocked by default in the httpd.conf. If your site is not blocking these already then you should find a default httpd.conf and compare it to the one you are using. There are several important security-related directives in the default that should only be changed or removed if you know exactly what they do. If something is missing from your httpd.conf then it’s likely that other things are missing too.

    Lastly, all of these directives can be placed in your httpd.conf or other Apache configuration file instead of in a .htaccess file. The advantage of this is that you can avoid the overhead of Apache having to search for and parse your .htaccess file on every request. Putting your configuration in httpd.conf rather than .htaccess will make your site faster.

  9. says

    @Creating a custom error page

    Have the php-code contain an automatic mailer, so when a visitor gets the error-page you will get an email automatically in your inbox with the type of error, environment information, visitor information, etc. whatever information you want ! :)

  10. says

    Great list – I will surely be referring back to this post, sometimes I need to include an htaccess file in my root directory, so will double check to make sure my commands and requests are correct. Thanks :)

  11. says

    This is a great list. Some things I knew and I learned a few more.

    I think a lot of people aren’t aware of what the .htaccess file is capable of and hopefully this page can open their eyes to what it can do.

  12. Tony says

    Hello and thanks for this useful list! I want to pw protect some .rar files in my site and i am a newbie when it comes to this. I understand i can use #15 as a solution but how do i go from there? Would i modify to secure.rar ? And how to add users and their passwords? Thank you in advance!

  13. says

    Good writeup but as someone said above, the header could be much better. There could be some exciting graphics because as people say presentation sells well.

  14. shankar says

    Hi ,
    Good note for seo

    Will i get the syntax of rewriting on IIS server. this code is applicable for apache server only i suppose.

    Please send it via mail if possible.

  15. RaphaelDDL says

    Lol once i’ve made a mistake writing a tag and then the server load went to the max and crashed apache..

    Server Admin almost kicked me out but he saw that i didn’t wanted to do that ,was just a mistake.

    So i say that this phrase below is crucial:
    “As htaccess files are very powerful, even a slightest syntax error can cause sever malfunction of your server. So it is crucial to take the backup copies of everything before you try the hacks and tricks on your hypertext access files.”

    Always backup your stuff and be sure to remove the file in the moment you see something is going wrong.

Leave a Reply

Your email address will not be published. Required fields are marked *