21 very useful htaccess tips & tricks

Apache web servers has a great way to manipulate information using .htaccess files. .htaccess (hypertext access) is the default name of a directory-level configuration file that allows for decentralized management of web server configuration. The .htaccess file is placed inside the web tree, and is able to override a subset of the server’s global configuration; the extent of this subset is defined by the web server administrator. The original purpose of .htaccess was to allow per-directory access control (e.g. requiring a password to access the content), hence the name. Nowadays .htaccess can override many other configuration settings, mostly related to content control, e.g. content type and character set, CGI handlers, etc.

Following are few very useful htaccess tricks.

1. Custom Directory Index Files

You can change a default index file of directory by using above snippet in your htaccess file. If a user request /foo/, Apache will serve up /foo/index.html, or whatever file you specify.

2. Custom Error Pages

You may want to redirect your users to an error page is any of the http errors like 404 occurs. You can use above snippet in htaccess file to map 404 error to error page errors/404.html. Also you may want to write a common page for all the http errors as follows:

3. Control access at files & directory level

.htaccess is most often used to restrict or deny access to individual files and folders. A typical example would be an “includes” folder. Your site’s pages can call these included scripts all they like, but you don’t want users accessing these files directly, over the web. In that case you would drop an .htaccess file in the includes folder with content something like this.

which would deny ALL direct access to ANY files in that folder. You can be more specific with your conditions, for instance limiting access to a particular IP range, here’s a handy top-level rule for a local test server.

Generally these sorts of requests would bounce off your firewall anyway, but on a live server they become useful for filtering out undesirable IP blocks, known risks, lots of things.

Sometimes, you will only want to ban one IP, perhaps some persistent robot that doesn’t play by the rules.

4. Modifying the Environment Variable

Environment variables contain information used by server-side includes and CGI. Set / Unset environment variables using SetEnv and UnSetEnv.

5. 301 Redirect using htaccess

If you want to redirect from an old document to new:

Use following for redirecting Entire Directory.

6. Implementing a Caching Scheme with .htaccess

Cache the static files and improve your website’s performance. (read this article: PHP, CSS, JS Compression for full implementation)

# year
<FilesMatch "\.(ico|pdf|flv|jpg|jpeg|png|gif|swf|mp3|mp4)$">
Header set Cache-Control "public"
Header set Expires "Thu, 15 Apr 2010 20:00:00 GMT"
Header unset Last-Modified
#2 hours
<FilesMatch "\.(html|htm|xml|txt|xsl)$">
Header set Cache-Control "max-age=7200, must-revalidate"
<FilesMatch "\.(js|css)$">
SetOutputFilter DEFLATE
Header set Expires "Thu, 15 Apr 2010 20:00:00 GMT"

7. Compress output using GZIP

Add following snippet into your htaccess file and compress all the css, js, html files with GZip compression.

<IfModule mod_gzip.c>
    mod_gzip_on       Yes
    mod_gzip_dechunk  Yes
    mod_gzip_item_include file      \.(html?|txt|css|js|php|pl)$
    mod_gzip_item_include handler   ^cgi-script$
    mod_gzip_item_include mime      ^text/.*
    mod_gzip_item_include mime      ^application/x-javascript.*
    mod_gzip_item_exclude mime      ^image/.*
    mod_gzip_item_exclude rspheader ^Content-Encoding:.*gzip.*

Above code works only if mod_gzip module is enabled in your webserver. You may want to add following snippet if your webserver provides mod_deflate support.

    SetOutputFilter DEFLATE
      SetEnvIfNoCase Request_URI  \
        \.(?:gif|jpe?g|png)$ no-gzip dont-vary
    SetEnvIfNoCase Request_URI  \
        \.(?:exe|t?gz|zip|gz2|sit|rar)$ no-gzip dont-vary

If your webserver does not support mod_deflate then you may want to use following snippet.

<FilesMatch "\.(txt|html|htm|php)">
	php_value output_handler ob_gzhandler

Read this articles for more detail: Compressing PHP, CSS, JavaScript(JS).

8. Redirect browser to https (ssl)

Add following snippet to your htaccess and redirect entire website to https.

9. Rewrite URLs using htacccess

Rewriting product.php?id=12 to product-12.html

Rewriting product.php?id=12 to product/ipod-nano/12.html

Redirecting non www URL to www URL

Rewriting yoursite.com/user.php?username=xyz to yoursite.com/xyz

Redirecting the domain to a new subfolder of inside public_html

10. Prevent Directory Listing

Add any of the following snippet to avoid directory listing.


Read this article on more details on Denying/Allowing directory listing.

11. Adding new MIME types

The type of file depends on the filename extension. Unrecognized file extensions are treated as text data, and corrupted on download.

12. Deny access to static file data

Denies any request for static files (images, css, etc) if referrer is not local site or empty.

13. Specify Upload file limit for PHP in htaccess

In the above .htaccess file, uploading capability is increased by the four parameter first one is maximum file size for uploading, second one is maximum size of the post data , third one is maximum time in seconds a script is allowed to run before it is terminated by the parser and last one is maximum time in seconds a script is allowed to parse input data such as like file uploads, POST and GET data.

14. Disallow Script Execution

15. Change Charset and Language headers

16. Set Timezone of the Server (GMT)

17. Force “File Save As” Prompt

18. Protecting a single file

Normally .htaccess applies to the entire directory. With the directive you can restrict it to specific files:

<Files quiz.html>
order deny,allow
deny from all
AuthType Basic
AuthName "Characterology Student Authcate"
AuthLDAP on
AuthLDAPServer ldap://directory.characterology.com/
AuthLDAPBase "ou=Student, o=Characterology University, c=au"
require valid-user
satisfy any

19. Set Cookie using htaccess

Set Cookie with environment variable

Set Cookie based on Request. This code sends the Set-Cookie header to create a cookie on the client with the value of a matching item in 2nd parentheses.

20. Send Custom Headers

21. Blocking request based on User-Agent Header

Feel free to bookmark this article.

Get our Articles via Email. Enter your email address.

You may also like...


  1. Nilesh Gamit says:

    Hey viral.. Its nice post. Regarding .htaccess, I am facing one issue from last few days. .htaccess files is getting deleted automatically every 2/3 days on server. I am very much sure its some server process initiated by hosting company. I contacted hosting provided but reply was not very helpful. I found that, some hosting provider do this but not clear documentation is there. If you have any idea, let me know.


  2. Viral Patel says:

    Hi Nilesh,
    I am not sure if I ever had this type of problem.!! This is quite strange and the webserver is seem to be culprit as you have mentioned in your comment.

    I will let you know if I find something in this direction. :)

  3. vats thakur says:

    Hello,really nice.

  4. beleneglorion says:


    just ti day in tips 13 that you need to put max php memory higher than max upload file size too if memory limit is 16M you can’t upload a 20M file.

  5. Ezuca says:

    It’s so comprehensive! Thanks

  6. Unknown says:

    Many many thanks for this useful tutorial.

  7. mahesh says:

    greate very useful tips

  8. WebDev says:

    Hi Viral,

    I am unable to find my website on Google after adding www on it.
    can u plz assist.

  9. Tony Hisir says:

    Thank you for the great information. I have so many redirects in htaccess. I wish I could cut down on them.

  10. elbakai says:

    Thank you very much, greate information and really it is very useful tips

  11. kiran says:

    i want to redirect this url

    that is in smarty ..i could not fount it out so please help me out thanks.

  12. Melanie says:

    Excellent Post, thank you very much. This is extremely useful information :)

  13. Renuraj Pingle says:

    Hey Viral!
    Really nice post buddy!
    Will you please help me,
    I am trying to block access of images in images folder. I have successfully blocked access of images folder but i cant do same for its content, so please tell me way to get this out!

  14. veer says:

    Hey Viral
    cookies not working in my website……when i check http://www.webpagetest.org Proper cookie usage: 53/100..how to add cookies proper cookies in .htacces

  15. parva says:

    good Tips. I’m using Cpanel, I have more than 10 wordpress websites installed in public html directory. Do I need to keep .htaccess file in Root or all websites folder.

  16. varsha says:

    hi viral,
    want to know how to remove index.php from any joomla website for joomla 2.5????? tell can u plz give me reply on my id [email protected] .

  17. Baronsed says:

    Can I please use (part of) this article for help files ? It would be Vim help files, the kind that is useful to sysadmin when they have to quickedit some .htaccess and suddenly don’t remember how to do one of these things. So they could just do :help htaccess, or :h deny.

    Thanks in advance.

  18. simptomi says:

    Good post. How to unset cookies. can you write about thath. Thanks

  19. nehal says:

    Hello! Thanks for the tricks. I am having a different issue. I have 4 domains 1 as primary (eg test.com). Now from the primary domain if you type other website container folder name (eg domain1) it displays the domain1 site. Like: http://www.test.com/domain1 So is there a way to block the particular folder from test.com. because if I use the block directory inside the “domain1” that will block the entire website. Plz help! thanks

  20. jack says:

    Thanks . You are a life saver

  21. jagadeesh says:

    very nice content.

  22. Gidon says:

    Superb ! I am sure your post can help me. I want to know the exact process of seo work for newly developed site. If any one knows what are the things should be done for new site.

  23. urjit says:

    How can i create .htaccess file in eclipse?

  24. Arun says:

    hey i am use this code to change my url – RewriteRule ^create_account/$ registration/index.php

    but in registration folder have js file and i m access this file using
    this path registration/account.js but i want change this path…?

  25. danger says:

    Hi all,

    I want that user can play song on my website, but can’t download with direct url ?

    How is that possible ?


  26. john says:

    can i use 2 .htaccess different coding files in public html folder
    if not then kindly put conditon if my site is offline then

    RewriteEngine on
    #RewriteBase /
    RewriteCond %{REQUEST_FILENAME} -f [OR]
    RewriteCond %{REQUEST_FILENAME} -d
    RewriteRule ^.*$ – [NC,L]
    RewriteRule .* index.php [L]


    RewriteEngine on
    #RewriteBase /
    RewriteCond %{REQUEST_FILENAME} -f [OR]
    RewriteCond %{REQUEST_FILENAME} -d
    RewriteRule ^.*$ – [NC,L]
    RewriteRule .* index.php [L]
    AddHandler application/x-httpd-php4 .php .php4 .php3

  27. john says:


    kindly put the correct conditon if and else
    if my site is offline then

    RewriteEngine on
    #RewriteBase /
    RewriteCond %{REQUEST_FILENAME} -f [OR]
    RewriteCond %{REQUEST_FILENAME} -d
    RewriteRule ^.*$ – [NC,L]
    RewriteRule .* index.php [L]


    RewriteEngine on
    #RewriteBase /
    RewriteCond %{REQUEST_FILENAME} -f [OR]
    RewriteCond %{REQUEST_FILENAME} -d
    RewriteRule ^.*$ – [NC,L]
    RewriteRule .* index.php [L]
    AddHandler application/x-httpd-php4 .php .php4 .php3

  28. Steve Mark says:

    almost htaccess setings include in this post thanks for share.

  29. fml says:


  30. Avesh says:

    Its really very nice post

  31. Sriya says:

    Thank you so much for the awesome information in this blog.

  32. Melody says:

    thanks Very helpful. But I still have a problem. How to set up a Block from the cookie reads the user’s default language? For example, if Request header / Cookie: country=CN then 403

  33. Mr Meta says:

    Nice but the

    http://www.example.com/some/index.html ->> http://www.example.com/some

    doesn’t work anymore in the new PHP version :(

  34. Sajjad says:

    Great & helpful .htaccess tutorial.
    I have created http://www.example.com/profile.php?id=2 to http://www.example.com/username using .htaccess rewrite rule. Thanks for sharing these tricks again.

  35. bRionZ says:

    from 2014 until now and next I always see this post while I forgot the rules. Thanks patel, You Rock!!!

Leave a Reply

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