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]

Source:

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

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>
<Files *.eps>
  ForceType application/octet-stream
  Header set Content-Disposition attachment
</Files>

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
</FilesMatch>

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

More posts about htaccess

Share this article

 
  • http://sayblog.me Chunlinsay

    “Create custom error pages” is very helpful for me to create a 404 page. Thanks for this great post!

  • http://www.purejavascript.com Justin

    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.

  • Jeroen

    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”?

    • http://www.wprecipes.com Jean-Baptiste Jung

      I’m not 100% sure, but as Google cache images, I’d say that they’ll place the images on Google images.

  • http://ten-321.com/ Curtiss Grymala

    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?

    • http://www.wprecipes.com Jean-Baptiste Jung

      Yes, in that snippet all other subdomains will be redirected as well.

  • http://www.manuel-strehl.de/ Manuel Strehl

    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

    • http://www.wprecipes.com Jean-Baptiste Jung

      Thanks, I corrected the snippet.

  • Michel

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

  • http://twitter.com/corestudiosnet Agis

    Great round-up! Thanks!

  • Bruno

    Really useful, thanks!

  • Dan B

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

    Thanks
    Dan

    • http://www.wprecipes.com Jean-Baptiste Jung

      Yes:

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

      :)

      • Blazej

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

        Like:
        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?

  • http://aroraworld.com Manish

    Hi,

    Regarding Remove www in url.
    I wonder why catswhocode has www in its url.

    Just wondering ….

    :)

    Cheers

    Manish

    • http://www.wprecipes.com Jean-Baptiste Jung

      It’s bad for SEO to use both www and non-www, but you can use www if you want, that will not hurt your SEO in any way.

  • http://www.chris-alix.com Pablinho

    Neat tips !! Was thinking on removing the .html extension from my files, big thanks !!

  • http://revisionx.ca Alec

    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!

  • http://alterimaging.com Vincent Ammirato

    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!

  • http://loneplacebo.com Tony

    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.

  • Andrew

    Don’t forget to escape the “.” in the regular expression!

  • Jordan

    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

      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.

  • Keika

    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

  • http://www.bluelinemedia.co.uk Simon Jackson

    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

  • http://www.designawebsite.com.au/ John

    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.

    John

  • http://www.kavamediagh.com Amazing

    my comment contained snippet which was stripped out.

    Order allow,deny

  • http://twitter.com/brynstarr Bryn Nicholas

    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?

  • http://blog.eglis.com Charles

    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 :)

  • Andrew

    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

  • http://www.bensky.co.uk Ben Sky

    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]

  • http://black-light-studio.com/ Ørjan

    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]

  • Nikolas

    Hello,
    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

  • http://theneworder.net Jon

    Very nice!

    The error page and hotlinking code are defiantly pro!

    Thanks!

  • Dan

    Very nice. Most of this tip apply to non-WP websites too.

  • http://www.aliendev.com Michael Youngblood

    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]

  • Olivia Copse

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

  • Jason

    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.

  • http://www.sethneal.com Seth Neal

    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?

  • http://www.monsejourlinguistique.com/ kennet

    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.

  • Marina de Wit

    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?

  • http://www.solutionsantirides.com/ Anthony

    Great round-up! Thanks!

  • James

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

    /products-1.html
    /products-1/
    /products-2.html
    /products-2/

    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!

  • http://ninjarocks.com Dave James

    “Remove file extensions from urls” and “Log PHP errors” was extremely helpful, thanks for that!

  • http://www.hmmultimedia.com Helder Martins

    Great snippets ;)

  • http://www.silverlizarddesign.com Zach Hicken

    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.

  • Mittul Chauhan

    Very useful tips again for htaccess .. i never know htaccess can also do such these things .. its flexible

  • http://funnyglobe.com ralph Cyprus

    the removing extension snippet isn’t working on my site. i have used your code but it is not working in my case

  • https://www.buylandingpagedesign.com/ Mrinal

    Learn a lot of things about .htacces, thanks for useful post, I love it.