10 useful .htaccess snippets to have in your toolbox

by Jean. 49 Comments -

.htaccess, the file which control the Apache webserver, is very useful and allows you to do a lot of things. In this article, I have compiled 10 .htaccess snippets that any web developer should have in his toolbox.

Before editing your .htaccess file, always make a backup so you can restore it if needed.

Remove www in url

For SEO reasons, you might always remove (or use) the www prefix in your urls. The following snippet will remove the www from your website url and redirect any url with the www to the non-www version.

RewriteEngine On
RewriteCond %{HTTP_HOST} !^your-site.com$ [NC]
RewriteRule ^(.*)$ http://your-site.com/$1 [L,R=301]

Source: http://css-tricks.com/snippets/htaccess/www-no-www/

Prevent hotlinking

Hotlinking is a bad practice that consist of using the images from another site on yours. When you’re hotlinked by someone else, your bandwidth is used for someone else profit. Of course, you may want to prevent hotlinkers. Just add the following snippet to your .htaccess file after replacing the example urls by your own urls.

RewriteEngine On
#Replace ?mysite\.com/ with your blog url
RewriteCond %{HTTP_REFERER} !^http://(.+\.)?mysite\.com/ [NC]
RewriteCond %{HTTP_REFERER} !^$
#Replace /images/nohotlink.jpg with your "don't hotlink" image url
RewriteRule .*\.(jpe?g|gif|bmp|png)$ /images/nohotlink.jpg [L]


Redirect all WordPress feeds to feedburner

Most bloggers are using Feedburner, a web service that lets you know how many people are reading your blog via feeds. If you’re using WordPress, you should redirect all WordPress feeds (rss, atom, etc) to your feedburner feed. Modify lines 2 and 3, and then paste this code to your .htaccess file.

<IfModule mod_alias.c>
 RedirectMatch 301 /feed/(atom|rdf|rss|rss2)/?$ http://feedburner.com/yourfeed/
 RedirectMatch 301 /comments/feed/(atom|rdf|rss|rss2)/?$ http://feedburner.com/yourfeed/

Source: http://www.wprecipes.com/how-to-redirect-wordpress-rss-feeds-to-feedburner-with-htaccess

Create custom error pages

Tired of the old errors pages of your site? Just create some html files with the look you want, upload them to your server, and add the following to your .htaccess file:

ErrorDocument 400 /errors/badrequest.html
ErrorDocument 401 /errors/authreqd.html
ErrorDocument 403 /errors/forbid.html
ErrorDocument 404 /errors/notfound.html
ErrorDocument 500 /errors/serverr.html

Source: http://css-tricks.com/snippets/htaccess/custom-error-pages/

Force download of specific files

When offering some files such as mp3s, eps or xls, for download on your site, you may force download instead of letting the browser decide what to do.
This snippet will force the download of .xls and .eps files from your server.

<Files *.xls>
  ForceType application/octet-stream
  Header set Content-Disposition attachment
<Files *.eps>
  ForceType application/octet-stream
  Header set Content-Disposition attachment

Source: http://www.givegoodweb.com/post/30/forcing-a-download-with-apache-and-htaccess

Log PHP errors

This snippet is an interesting way to log errors from your php file into a log file. Just create a php_error.log file somewhere on your server, and add the snippet to your .htaccess file. Don’t forget to modify the log file location on line 7.

# display no errs to user
php_flag display_startup_errors off
php_flag display_errors off
php_flag html_errors off
# log to file
php_flag log_errors on
php_value error_log /location/to/php_error.log

Source: http://css-tricks.com/snippets/htaccess/php-error-logging/

Remove file extensions from urls

File extensions may be useful to developers, but there’s absolutely no need for your site visitors to be able to see them. This snippet will remove the .html extension on any html files. Of course, this code can be easily adapted to remove extensions from other file extensions such as php.

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.html -f
RewriteRule ^(.*)$ $1.html
# Replace html with your file extension, eg: php, htm, asp

Source: http://eisabainyo.net/weblog/2007/08/19/removing-file-extension-via-htaccess

Prevent directory listing

On your web server, when a directory do not have an index file, Apache automatically create a list of all files from the current directory. If you do not wish that anyone can see which files are on your server, just add the following code to your .htaccess file to prevent automatic directory listing.

Options -Indexes

Reduce pages weight by compressing static data

Do you know that it is possible to send compressed data to the visitors, which will be decompressed by the client? This code will definitely save you (and your visitor) bandwidth and reduce your pages weight.

AddOutputFilterByType DEFLATE text/html text/plain text/xml application/xml application/xhtml+xml text/javascript text/css application/x-javascript
BrowserMatch ^Mozilla/4 gzip-only-text/html
BrowserMatch ^Mozilla/4.0[678] no-gzip
BrowserMatch bMSIE !no-gzip !gzip-only-text/html

Automatically add utf-8 charset to files

In order to avoid encoding problems, you can force a specific encoding directly on your .htaccess file. That way, you’ll ensure that your html documents will always render correctly, even if your forget to add a <meta http-equiv="Content-Type"> directive on your html pages.

<FilesMatch "\.(htm|html|css|js)$">
AddDefaultCharset UTF-8

Source: http://www.askapache.com/htaccess/setting-charset-in-htaccess.html

More posts about htaccess

Share this article


Comments (49) - Leave yours

  1. Justin said:

    Thanks for posting this. It’s nice to have these common uses all in one post.

    Every new project I either copy and paste snippets from previous projects or go searching on blogs…regular expressions is something I don’t use often enough to master.

  2. Jeroen said:

    Thanks great bunch of snippets!
    Just a quick question:
    When you’re preventing image hotlinkers, do you also prevent google from placing your images in their image-search? If yes, how can you put google on the “white-list”?

  3. Curtiss Grymala said:

    Very nice collection of tips. Quick question, though: Won’t the snippet you provided for “Remove www in url” also redirect all other subdomains to the root domain? It might be better to explicitly use the www in the conditional statement, wouldn’t it?

  4. Manuel Strehl said:

    Ahem, sending CSS and JS files as “text/html”, as does the last snippet, really doesn’t qualify as useful tip. A much more sensible directive would be

    AddDefaultCharset utf-8

  5. Michel said:

    Is it also possible to redirect to a page “index.html” instead of the default “index.php” ?

  6. Dan B said:

    Thanks for the tip on Removing the www in an url, is there a reverse version? One that adds the www if its missing?


      • Blazej said:

        Is it possible to redirect in the same way to https?

        RewriteEngine On
        RewriteCond %{HTTP_HOST} ^your-site.com [NC]
        RewriteRule ^(.*)$ https://www.your-site.com/$1 [L,R=301]

        Or is there a better way to redirect all not-https calls on https?

  7. Alec said:

    Great list! I’ve used many of these snippets before, but a few you have listed here i’d never even heard of. I’ll be bookmarking this page for sure!

  8. Vincent Ammirato said:

    Thank you for this great list. I’m in and out of .htaccess files all the time and this helps greatly. I also teach a basic web class and I’m bookmarking this for next semester!

  9. Tony said:

    For forcing the removal of WWW, Google Webmaster Tools now lets you set that as a preference for search results: https://skitch.com/brevityness/fn6rs/webmaster-tools-settings

    It wont stop someone from visiting www.yourdomain.com though but it’ll reduce the likelihood of it happening when they find you via Google.

  10. Jordan said:

    I’ve been reading that using htaccess greatly reduces performance and that these techniques should be placed in Apache’s config files instead.

    • Chris Sedlmayr said:

      Yes, .htaccess files are passed at every request, whereas your .conf file will be cached by Apache so its always best to have it there. shouldn’t be using .htaccess at all unless you don’t have access to the .conf files.

  11. Keika said:

    Hi, i’m having a small issue with the hotlink. I tried hotlinking one of my images from one blog to another, and it seems that the nohotlink.jpg image is sent as text/html, so it doesn’t display on the hotlinking site.

    Any idea ?

    My paths are correct I checked.

    Thank you anyway, those snippets are very useful

  12. Simon Jackson said:

    Another good one is to rewrite your index page to the web root. If your site has links using both the domain name on its own and the index filename (i.e. http://www.yourwebsite.com and http://www.yourwebsite.com/index.php) then search engines will treat these as two separate pages. This isn’t ideal for SEO as you want all these inbound links to point to the same “page”.

    The following code will do the trick. It should be put at the bottom of the htaccess file after all the other redirects.

    RewriteRule ^$ index.php

  13. John said:

    Hi Jean,

    Before reading your post i know only 1 thing about .htaccess and that is Remove www in url or adding www in url, both things can be possible with the help of .htaccess.
    All other point are very useful to me.
    Thanks for sharing very nice information with us.


  14. Bryn Nicholas said:

    Great article – has anybody managed to restrict, for example, direct access to a .flv file, but allow that file to be called by a particular (dynamic) url on the server?

  15. Charles said:

    A long long time a go it was told to always use www.example.com as www standed for world wild world when you read up into dns you start to understand that the example.com version wasn’t meant to be.

    example.com is the Zone
    then you add subdomains for your different services.

    I find it sexier with the www, so i use that sniplet on my sites :)

  16. Andrew said:

    Your first rule (strip www.) isn’t very good. It will redirect all subdomains and you have to explicitly define the host twice:

    RewriteEngine On
    RewriteCond %{HTTP_HOST} ^www\.$ [NC]
    RewriteRule ^(.*)$ http://your-site.com/$1 [L,R=301]

    For more great .htaccess ideas, check the .htaccess file that comes with HTML5 Boilerplate – https://github.com/paulirish/html5-boilerplate/blob/master/.htaccess

  17. Ben Sky said:

    Here’s one to add the WWW. without specifying the host!

    RewriteEngine On
    RewriteCond %{HTTP_HOST} !^www [NC]
    RewriteRule ^([a-z0-9-\./]+)?$ http://www.%{HTTP_HOST}/$1 [R=301,L]

  18. Ørjan said:

    When removing WWW or doing the opposite I prefer to use

    #www – Resolve (take away WWW from the URL)
    RewriteEngine on
    RewriteCond %{HTTPS} off
    RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
    RewriteRule ^(.*)$ http://%1/$1 [R=301,L]
    RewriteCond %{HTTPS} on
    RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
    RewriteRule ^(.*)$ https://%1/$1 [R=301,L]

  19. Nikolas said:

    Thank you for your nice post. I have a question regarding the redirection from non-www to www pages.
    I found many resources online and all have slightly different solutions. For example:

    RewriteCond %{HTTP_HOST} ^domain.com$
    RewriteRule ^(.*)$ “http\:\/\/www\.domain\.com\/$1″ [R=301,L]

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

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

    RewriteCond %{http_host} ^domain\.com [nc]
    RewriteRule ^(.*)$ http://www.domain.com/$1 [R=permanent,nc,L]

    So, which one is the more appropriate to use?
    Thank y ou for your answer

  20. Michael Youngblood said:

    Oh man, I can’t tell ya how many times I have needed some of these. Oh, and with the non-www snippet, I usually use the other way, and make non-www = www. either way, the intent and solution to duplicate content in Google is there.

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

  21. Olivia Copse said:

    Thank you for a really useful post – especially the hotlinking block. Even I can follow it – and that’s saying something :)

  22. Jason said:

    Can someone point me in the direction? I wrote a WordPress plugin that requires adding a line of code to the .htaccess files. I want to be able to have that line added just by activating the plugin rather that the user manually adding the line of code. I can’t find any info on how to check the presence of .htaccess, append it, etc.

  23. Seth Neal said:

    Wow! Great post!

    I couldn’t get the Prevent Hotlinking tip to work. I run on WordPress; do I need to have the image in the directory the hot linked image is in?

  24. kennet said:

    i think this one it is apropiate to use:

    RewriteCond %{HTTP_HOST} !^www.your_domain.com$
    RewriteRule ^(.*)$ http://www.your_domain.com/$1 [R=301]

    please let me know if it worked.

  25. Marina de Wit said:

    Is there a way to combine the remove url with the remove file extensions?
    and Boilerplate uses this for www.removal:

    RewriteCond %{HTTPS} !=on
    RewriteCond %{HTTP_HOST} !^www\..+$ [NC]
    RewriteCond %{HTTP_HOST} (.+)$ [NC]
    RewriteRule ^ http://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

    How to combine it with this:
    Options +FollowSymlinks
    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME}\.htm -f
    RewriteRule ^(.*)$ $1.htm

    Does anyone knows?

  26. James said:

    I love the idea of removing the file extension, however I have a number of files and folders with the same name:


    Removing the file extension now instead lists the directory in the browser – is there a way to make /products-1/ open the html file (without the extension), instead of listing the directory?

    Many thanks!

  27. Zach Hicken said:

    Once I learned how to use htaccess it took my development and even design to a whole new level. It is nice to have these really common snippets together in one place.

Leave a Reply

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

Please respect the following rules: No advertising, no spam, no keyword in name field. Thank you!