Development

The Definitive Guide to htaccess Techniques: Do’s and Don’ts

August 10th, 2009

Of all the elements of web design and coding, htaccess can be one of the most intimidating. After all, it’s an incredibly powerful tool and one that has the potential to completely break your site if you’re not careful.

Below are a dozen basic htaccess techniques and tips to get you started. They’re not nearly as intimidating as many people expect, and if you study the code for a few minutes, I’m sure you’ll quickly grasp exactly how they work and why.

After that are a few bewares and don’ts for working with htaccess to help keep you out of trouble, and some more resources for further working with htaccess.

htaccess Techniques

12 Basic htaccess Tips:

1. Create a custom error page.

.htaccess on a Linux Apache server makes it easy to create your own custom error pages. Just create your custom error page files and then add this code to your .htaccess file:

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

(Obviously you should replace the “/500.php” or whatever with your own file path and name.)

2. Prevent directory browsing.

If you don’t include an index file in a directory, visitors can browse the directory itself. But preventing that is as easy as adding a single line to your .htaccess file:

Options All -Indexes

3. Set the default page of each directory.

If you don’t want to use an index page in each directory, you can set the default page visited when someone reaches (like an about page or a page offering the newest content) that directory by adding this:

DirectoryIndex news.html

(And of course you’d replace the “news.html” bit with whatever you want to use as the default.)

4. Set up a 301 redirect.

If you move around the structure of your site and need to redirect some old URLs to their new locations, the following bit of code will do so for you:

Redirect 301 /original/filename.html http://domain.com/updated/filename.html

5. Compress file output with GZIP.

You can add the following code to your htaccess file to compress all of your JavaScript, CSS and HTML files using GZIP.

<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.*
</IfModule>

secure https connection

6. Redirect to a secure https connection

If you want to redirect your entire site to a secure https connection, use the following:

RewriteEngine On
RewriteCond %{HTTPS} !on
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}

7. Block script execution.

You can stop scripts in certain languages from running with this:

Options -ExecCGI
AddHandler cgi-script .pl .py .php .jsp. htm .shtml .sh .asp .cgi

Just replace the types of scripts you want to block.

8. Force a file to download with a “Save As” prompt.

If you want to force someone to download a file instead of opening it in their browser, use this code:

AddType application/octet-stream .doc .mov .avi .pdf .xls .mp4

9. Restrict file upload limits for PHP.

You can restrict the maximum file size for uploading in PHP, as well as the maximum execution time. Just add this:

php_value upload_max_filesize 10M
php_value post_max_size 10M
php_value max_execution_time 200
php_value max_input_time 200

Line one specifies the maximum file size for uploading; line two is the maximum size for post data; line three is the maximum time in seconds a script can run before it’s terminated; and line four is the maximum amount of time in seconds a script is allowed to parse input data.

10. Enable File Caching.

Enabling file caching can greatly improve your site’s performance and speed. Use the following code to set up caching (changing the file types and time values to suit your site’s needs):

#cache html and htm files for one day
<FilesMatch ".(html|htm)$">
Header set Cache-Control "max-age=43200"
</FilesMatch>

#cache css, javascript and text files for one week
<FilesMatch ".(js|css|txt)$">
Header set Cache-Control "max-age=604800"
</FilesMatch>

#cache flash and images for one month
<FilesMatch ".(flv|swf|ico|gif|jpg|jpeg|png)$">
Header set Cache-Control "max-age=2592000"
</FilesMatch>

#disable cache for script files
<FilesMatch "\.(pl|php|cgi|spl|scgi|fcgi)$">
Header unset Cache-Control
</FilesMatch>

(Time shown for max-age is in seconds.)

11. Protect your site from hotlinking.

The last thing you want is for those stealing your content to also be able to embed the images hosted on your server in their posts. It takes up your bandwidth and can quickly get expensive. Here’s a way to block hotlinking within htaccess:

RewriteEngine On
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^http://([ -a-z0-9]  \.)?domain\.com [NC]
RewriteRule \.(gif|jpe?g|png)$ - [F,NC,L]

(Of course you’ll want to replace the domain\.com with your own domain name.)

12. Disguise your file types.

You can disguise all of your file types by making them appear as PHP files. Just insert this snippet in:

ForceType application/x-httpd-php

htaccess Techniques

8 Common htaccess Mistakes and Don’ts:

  • Be careful of spelling- .htaccess is not forgiving of spelling errors.
  • htaccess is case sensitive. If something is shown in the examples with a capital letter, make sure it’s capitalized in your htaccess file.
  • Consider your caching needs carefully before setting it up. If your site is almost entirely static, you can set longer cache times. If your site changes daily, make sure you adapt which files will cache for how long. There’s nothing worse as a visitor than coming back to a site thinking there’s been an update and not seeing it.
  • Don’t forget to comment out your notes within the file. This is done by adding a # before the comment line.
  • Always test your site immediately after making any changes to your htaccess file. One mistyped character could make the difference between your site working and being down for hours before you realize what’s happened.
  • On that note, always make sure you backup your htaccess file before making any changes. That way, if there is a problem, you can easily swap back in the old file.
  • Make sure any essential htaccess functions you’ve included are cross-browser compatible. There are certain things some browsers just won’t support (one example is with certain methods for forcing file downloads).
  • Remember when protecting a web directory with htaccess, that unless it’s restricted to https access, the password could be sniffed (as your authentication will be done over an un-secure connection).
  • More Resources:

    Author: Cameron Chapman

    Cameron Chapman is a writer, blogger, copyeditor, and social media addict. She’s been designing for more than six years and writing her whole life. If you’d like to connect with her, you can follow her on Twitter or at her Personal Website.

    Write for Us! We are looking for exciting and creative articles, if you want to contribute, just send us an email.

    The jungle is alive: Be it a collaboration between two or more authors or an article by an author not contributing regularly. In these cases you find the Noupe Editorial Team as the ones who made it. Guest authors get their own little bio boxes below the article, so watch out for these.

69 comments for „The Definitive Guide to htaccess Techniques: Do’s and Don’ts
  1. joyoge designers' bookmark on August 10th, 2009 at 4:06 am

    useful techniques, thank you so much..

  2. Oliver Nassar on August 10th, 2009 at 4:15 am

    Great post. Rewrite rules are a little more advanced, but would be cool to see a post about them.

  3. Joffrey on August 10th, 2009 at 6:20 am

    Great, maybe the best guide I’ve ever seen.
    Thanks! :)

  4. Matt on August 10th, 2009 at 6:35 am

    Excellent post. Great to have all these useful htaccess techniques in one place with clear instructions.

  5. Alex on August 10th, 2009 at 8:26 am

    Great tips!

    Something to keep in mind is that each of of these tips can be used in the regular Apache configuration file. The syntax is the same.

    One thing to keep in mind when thinking about the do’s and dont’s is that whenever possible add these changes to the Apache config file instead of a .htaccess file.

    Additional overhead is introduced by enabling the .htaccess file.

  6. Jeff Kee on August 10th, 2009 at 9:04 am

    Well organized, well written, easy to understand – arguably the best quick guide for .htaccess I’ve seen.

  7. Marie Poulin on August 10th, 2009 at 10:27 am

    Where were you 6 months ago??
    Seriously, really useful stuff,
    much appreciated!

  8. Gregory Raby on August 10th, 2009 at 12:45 pm

    Much needed thanks, although enabling GZIP via Htaccess would deserve a little more details. 1&1 users won’t go far with the above example.

  9. shin on August 10th, 2009 at 1:18 pm

    Question to Cameron.
    In tip 11, you wrote ‘(Of course you’ll want to replace the domain\.com with your own domain name.)’
    Do I need to replace like this? ‘http://www.mywebsite\.com’
    Do I need http://www. ?

    Thanks for the article. I learned something new today. :-)

    • Cameron Chapman on August 10th, 2009 at 11:32 pm

      You would just change the domain.\com to yoursite\.com (leaving in the “\.”) without the “http://www.” (because that’s already included in that line of code). So it would look like this:

      http://( -a-z0-9] \.)?noupe\.com [NC]

      You can also do it like this:

      http://(www\.)?noupe\.com [NC]

    • Mike Stenger on August 11th, 2009 at 6:51 am

      Yeah, same thing I’m trying to figure out. Changed “domain” to mine, added it and then got 500 error so that way definitely doesn’t work.

    • Helen on September 5th, 2009 at 5:24 am

      I have another way to prevent hotlinking which enables Google and Bing to hotlink, because most of the tips you can find on the web usually don’t work. Normally, Google has no problem with anti-hotlinking, but Bing has. Yahoo more often than not can hotlink, but sometimes not.

      RewriteEngine On
      RewriteCond %{HTTP_REFERER} !^http://(.+\.)?mydomain\.com/ [NC]
      RewriteCond %{HTTP_REFERER} !^http://(.+\.)?google\.(.+)/ [NC]
      RewriteCond %{HTTP_REFERER} !^http://(.+\.)?(.*\.)?google\.(.+)/ [NC]
      RewriteCond %{HTTP_REFERER} !^http://(.+\.)?bing\.(.+)/ [NC]
      RewriteCond %{HTTP_REFERER} !^http://(.+\.)?(.*\.)?bing\.(.+)/ [NC]
      RewriteCond %{HTTP_REFERER} !^$
      RewriteRule .*\.(jpe?g|gif|png)$ /error/copyright.bmp [L]

      Important: The replacement-image must not have the one of the forbidden suffixes. if you normally use .jpg, you can use .jpe or .bmp.

  10. mahesh Prasad on August 10th, 2009 at 1:52 pm

    gr8 post!
    thanks…

  11. Illi.Pro on August 10th, 2009 at 2:01 pm

    Hey! Nice techniques but i wanna know if you can show me something that i want a lot.. it’s about to show a maintenance page.. the idea is that i create a file (www.myblog.com/maintenance.html) and via .htaccess i make that when someone visit any post (www.mypage.com/somepostinmyblog.html) it will show the maintenance page but the important thing is that in the addres bar, the url doesn’t show my maintenance.html page url, instead, it still showing the url of the post (www.mypage.com/somepostinmyblog.html) but with the content of (www.mypage.com/maintenance.html).. hope you understand me and help me :)!

    • Cameron Chapman on August 10th, 2009 at 11:45 pm

      I’m honestly not sure about this one. I would start by searching for tips on URL masking. It might be possible to do this with mod_rewrite. I know it can be done, but I’m not sure if htaccess is the best way to go about it or if there’s a better solution. It’s not something I’ve ever needed to do before.

  12. Jamie Allsop on August 10th, 2009 at 2:25 pm

    These are some really useful techniques and are well written and easy to understand. Thanks for the great article.

  13. Mujeeb Khumawala on August 10th, 2009 at 2:35 pm

    This definately Rocks!

    Thanks.

  14. Connie on August 10th, 2009 at 3:04 pm

    Unfortunately I cannot print this page.

    Print Preview in Firefox 3.0.13 only shows 2 pages….

    • Connie on August 10th, 2009 at 3:27 pm

      in Opera 9.6.2 it is ok
      will check if a Firefox-Update will help me ;=)

  15. ahmet alp balkan on August 10th, 2009 at 3:48 pm

    It is great, thanks.

  16. Susie on August 10th, 2009 at 4:43 pm

    This is a great resource, thanks so much! its given me some great ideas on things I need to do.

  17. Dinakar on August 10th, 2009 at 6:07 pm

    Great Article for newbies !! thank you very much.. !! keep it up

  18. KubX on August 10th, 2009 at 6:10 pm

    Thank you ;)

  19. Jef on August 10th, 2009 at 6:17 pm

    Nice tips, I will look to try some! Thanks

  20. Ted Goas on August 10th, 2009 at 6:44 pm

    Wow, this is an absolutely fantastic collection of commands that designers can reference. Great explanations! Thanks!

  21. skullpat on August 10th, 2009 at 6:49 pm

    Nice list, good to keep it on a second hand ;)
    Thanks !!

  22. Jack Humphrey on August 10th, 2009 at 7:13 pm

    I don’t believe I’ve ever seen all this in one place before! Bookmarked!

  23. Ahmed on August 10th, 2009 at 8:38 pm

    Nice Info Collection Thanks for Sharing it

    • Marden on May 4th, 2011 at 5:34 pm

      This forum needed skhanig up and you?ve just done that. Great post!

  24. Jasmine on August 10th, 2009 at 9:41 pm

    Quite impressed! All I googled wasn’t as useful as this article :D

  25. Lisa on August 11th, 2009 at 12:46 am

    This is awesome! Great resource. Thank you for all of this. Definitely bookmarking.

  26. Dan Sargeant on August 11th, 2009 at 6:53 am

    Great reference list. Thanks. Bookmarked!

  27. Web design glossop on August 11th, 2009 at 5:25 pm

    Great article thanks for sharing – #5. Compress file output with GZIP is a great tip I wasnt aware of this.

  28. D on August 11th, 2009 at 6:49 pm

    You can also block a range of IP addresses from visiting your site. This comes in handy when people in China, for example, only come to your site to steal the design/code/articles.whatever.

    For my portfolio site it’s a no brainer. Do people in China, India, Brazil, etc really need to see my US web design portfolio site? Probably not.

    This site helps generate an htaccess deny list. I’m sure there are ways around it but it helps.

    http://www.countryipblocks.net/

  29. Mike Cherim on August 11th, 2009 at 7:53 pm

    Outstanding overview. Thanks.

  30. Vishal on August 12th, 2009 at 1:20 am

    Hi there,

    Seems like [code]
    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 rspheader ^Content-Encoding:.*gzip.*
    [/code]

    Does not seem to work. I tried adding these lines in .htaccess, but no success. Any idea on what I am missing?

    Thanks.

    • Susheel Chandradhas on August 19th, 2009 at 6:44 pm

      Vishal,

      If you’re on a shared hosting service, and your service provider has disabled the mod_gzip apache module, then it won’t work.

  31. Webhostright on August 12th, 2009 at 3:12 am

    Thanks, anything htaccess is something that i always deal with very slowly, usually worried about making a mess of something so i tend to read through things a few times.

    Thanks for this info, very useful and practical stuff too.

  32. Bob on August 12th, 2009 at 9:29 pm

    BTW a small errata;
    Options All -Indexes
    is a don’t; mixing +/- options and non-+/- options is evil syntax, see https://issues.apache.org/bugzilla/show_bug.cgi?id=33078

    Setting MIME-typs to invoke hanlers (ForceType application/x-httpd-php) is bad coding, too. You should use SetHandler.

    RewriteCond %{HTTPS} !on
    Using the lex. equal (strcmp) is more efficient than a regular expression:
    RewriteCond %{HTTPS} !=on

    (and others)
    if you’d like to match a period and not any character, you should use

    And of course, .htaccess files are always a don’t, if one has access to the httpd.conf

  33. Geoserv on August 13th, 2009 at 4:33 pm

    Excellent article. I find the gzip trick actually slows my site down as opposed to speeding it up.

  34. alexpts on August 14th, 2009 at 9:34 pm

    It is great, thanks ))

  35. Maher Salam on August 16th, 2009 at 6:37 pm

    Thanks for this great tips .

    I’m having a problem with the caching method , I knew this technique before reading this article and I’m using it in my website , but the visitors can’t see the changes when I try to update something in the css or the javascripts of my website , so how can I flush the cache ??

  36. Jason on August 18th, 2009 at 2:15 am

    That’s an excellent guide for anyone. Thanks!

  37. Driveways on August 20th, 2009 at 9:37 pm

    thanks for sharing a great article :)

  38. Paul Hancox on August 24th, 2009 at 3:33 am

    Thanks for the useful guide. I have fiddled out with htaccess before but all this extra stuff is useful to know.

  39. Me on August 24th, 2009 at 9:37 pm

    I intend to bookmark this page therefore I add my own tricks :)

    Prevent a txt file (or any file, just change txt to something else) to be loaded

    Order allow,deny
    Deny from all

    password protect one file :

    AuthType Basic
    AuthName “logged”
    AuthUserFile /whateverrep/.htpasswd
    require valid-user

    dont forget to add a .htpasswd with a proprer login/pasword inside

  40. odin on September 1st, 2009 at 4:14 am

    Regarding (#12) ForceType, you might want to limit it by Directory or Files block so you don’t parse files as PHP that you didn’t mean to (e.g., images).

    Regarding (#11) note that some security software and firewalls will block or change the referrer and deny legitimate access to your content. You need to weigh the cost/benefit of this solution to your specific application.

    The “High Performance Web Sites” O’Reilly book is a good reference for more info on these topics and more. For the more advanced topics (rewrites, compression, etc.), I would highly recommend fully understanding the impact (client, server, SEO, etc.) and technology before implementing on any public site.

  41. affordable web design on September 5th, 2009 at 12:21 am

    A few things there I forgot about. “logging into the FTP promptly”. Thanks for the article!

  42. Timo Körber on September 8th, 2009 at 4:56 pm

    Thanks for this. I’ve been looking for something like that for so long. ;)

  43. test on November 25th, 2009 at 2:53 am
  44. Harjot Singh Chopra on January 27th, 2010 at 9:38 pm

    Thanks a lot dear. These are very useful.

  45. Panakj on March 15th, 2010 at 4:30 am

    much appreciated!

  46. Tanzeel Niazi on March 24th, 2010 at 11:29 am

    Some times my website blackouts, giving me “500 Internal Server Error”, Googled it but didn’t find a proper solution on .htaccess Dos and Dont’s. Thanks, we’ll definitely keep these tips in mind.

  47. Harsha M V on June 3rd, 2010 at 6:47 am

    awesomw tips.. thanks for the tips

  48. chris on June 11th, 2010 at 8:06 am

    Thanks,
    I gladly clicked on all your banners ;-)

  49. Louise on August 21st, 2010 at 3:17 am

    Thanks for the hotlinking tip. We were just about to create some rude images for the naughty people hotlinking from one of our sites!

  50. himmu on September 3rd, 2010 at 11:22 am

    This is some advance info and helps me learn lille ahead of what i was thinking all these days. Might ask my programmer to check this article so that he can get some good knowledge about the above mentioned tips n tricks.

  51. Sandeepya on October 2nd, 2010 at 6:39 am

    really useful..:)

  52. caraga on October 12th, 2010 at 8:17 am

    this is what im looking for!

  53. zaira on December 20th, 2010 at 4:28 am

    These are some really useful techniques and are well written and easy to understand. Thanks for the great article.

  54. Arron Hillyer on February 4th, 2011 at 6:42 am

    Generally I do not learn post on blogs, but I wish to say that this write-up very pressured me to take a look at and do so! Your writing style has been surprised me. Thank you, quite nice article. Executive Elite, 18a Greycoat Gardens, Greycoat Street, London, SW1P 2QA, 028 2088 0135

  55. Jatin on April 30th, 2011 at 8:13 am

    OMG, htaccess :( I am definitely no good at writing htaccess rules. Great tutorial BTW, it helped me clear some of my doubts.

  56. Carol on May 12th, 2011 at 10:06 pm

    The rule to force download doesn’t seem to work. I tried on Firefox and IE9 and I can still open the file on the browser.

  57. ronaldo on June 10th, 2011 at 6:32 pm

    Thanks for the post, was an interesting read.

  58. Arif Chasan on June 13th, 2012 at 5:29 am

    i bookmark this.
    thank you very much.. :*

  59. Patrick Dey on July 13th, 2012 at 6:00 pm

    Great post, Cameron. You have made a difficult subject look easy. I also like the list of common htaccess mistakes to avoid.

  60. Mimi on August 10th, 2012 at 12:45 pm

    Thank you! htaccess files can be a pain in the you know what and mine has been today. You have helped resolved an annoying issue.

  61. Sarah West on December 22nd, 2012 at 11:01 am

    Do you happen to know the impact of letting something like Magento handle the 301 redirects over .htaccess in terms of performance and SEO? One example I’ve been made aware of today is the non-www to www 301 redirect? I’ve had a play doing that in the htaccess but managed to take the site offline!

  62. chetan on January 2nd, 2013 at 5:22 pm

    I want to change the my url
    from: http://domain-name/dir/page1.php
    to: http://domain-name/dir/?page1

    For this i have written following code in my .htaccess file:

    RewriteEngine on
    RewriteCond %{THE_REQUEST} ^GET\ /[^?\s]+.php
    RewriteRule (.).php$ /dir/?$1 [L,R=301]
    RewriteRule (.)/$ $1.php [L]

    The URL gets changed to what i want perfectly. But the page remains the same.
    For example,
    Suppose i m on page1.php. When i click on menu ‘page2′ (page2),
    the url gets changed to “domainname/dir/?page2? but browser dont show the ‘page2′ contents.
    I am not using any CMS. Its just a simple php website.

    I want to change the my url
    from: http://domain-name/dir/page1.php
    to: http://domain-name/dir/?page1

    For this i have written following code in my .htaccess file:

    RewriteEngine on
    RewriteCond %{THE_REQUEST} ^GET\ /[^?\s]+.php
    RewriteRule (.).php$ /dir/?$1 [L,R=301]
    RewriteRule (.)/$ $1.php [L]

    The URL gets changed to what i want perfectly. But the page remains the same.
    For example,
    Suppose i m on page1.php. When i click on menu ‘page2′ (page2),
    the url gets changed to “domainname/dir/?page2? but browser dont show the ‘page2′ contents.
    I am not using any CMS. Its just a simple php website.
    plz help me