10+ .htaccess snippets to optimize your website

by Jean. 26 Comments -

Apache .htaccess file is at the heart of your web server and control how your website will react to different actions performed by your visitors. I’ve compiled 10+ awesome .htaccess snippets to optimize your website in many ways: Redirections, performances, ease of use… Enjoy!

All of the snippets below have to be pasted into your .htaccess file, which is located on the root of your Apache server.
Waring: Always make sure you have a working backup before editing your .htaccess file!

Force trailing slash

Many clients of mine asked me for always having a trailing slash at the end of their urls. Looks like it’s great for SEO. The following snippet will alwyas add a trailing slash to your site urls.

<IfModule mod_rewrite.c>
 RewriteCond %{REQUEST_URI} /+[^\.]+$
 RewriteRule ^(.+[^/])$ %{REQUEST_URI}/ [R=301,L]
</IfModule>

Source: http://perishablepress.com/code-snippets/

Prevent hotlinking

Hotlinking (the act of using images from another site than yours) is unfortunely a common practice which can waste lots of your precious bandwidth. This useful snippets will redirect all hotlinked images to a specific image, defined on line 6.

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: http://www.wprecipes.com/how-to-protect-your…

Redirect mobile devices

If your site is not using responsive web design yet, it could be very useful to be able to redirect mobile device to a mobile-specific version of your website.

RewriteEngine On
RewriteCond %{REQUEST_URI} !^/m/.*$
RewriteCond %{HTTP_ACCEPT} "text/vnd.wap.wml|application/vnd.wap.xhtml+xml" [NC,OR]
RewriteCond %{HTTP_USER_AGENT} "acs|alav|alca|amoi|audi|aste|avan|benq|bird|blac|blaz|brew|cell|cldc|cmd-" [NC,OR]
RewriteCond %{HTTP_USER_AGENT} "dang|doco|eric|hipt|inno|ipaq|java|jigs|kddi|keji|leno|lg-c|lg-d|lg-g|lge-" [NC,OR]
RewriteCond %{HTTP_USER_AGENT}  "maui|maxo|midp|mits|mmef|mobi|mot-|moto|mwbp|nec-|newt|noki|opwv" [NC,OR]
RewriteCond %{HTTP_USER_AGENT} "palm|pana|pant|pdxg|phil|play|pluc|port|prox|qtek|qwap|sage|sams|sany" [NC,OR]
RewriteCond %{HTTP_USER_AGENT} "sch-|sec-|send|seri|sgh-|shar|sie-|siem|smal|smar|sony|sph-|symb|t-mo" [NC,OR]
RewriteCond %{HTTP_USER_AGENT} "teli|tim-|tosh|tsm-|upg1|upsi|vk-v|voda|w3cs|wap-|wapa|wapi" [NC,OR]
RewriteCond %{HTTP_USER_AGENT} "wapp|wapr|webc|winw|winw|xda|xda-" [NC,OR]
RewriteCond %{HTTP_USER_AGENT} "up.browser|up.link|windowssce|iemobile|mini|mmp" [NC,OR]
RewriteCond %{HTTP_USER_AGENT} "symbian|midp|wap|phone|pocket|mobile|pda|psp" [NC]
#------------- The line below excludes the iPad
RewriteCond %{HTTP_USER_AGENT} !^.*iPad.*$ 
#-------------
RewriteCond %{HTTP_USER_AGENT} !macintosh [NC] #*SEE NOTE BELOW
RewriteRule ^(.*)$ /m/ [L,R=302]

Source: http://snipplr.com/view.php?codeview&id=55114

Force download of a specific filetype

For some reasons you may need to force download of specific files, such as MP3s or XLS. This code snippets will prevent your visitor’s browser to read the file and force downloading instead.

<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://snipplr.com/view.php?codeview&id=54752

Cross Domain Font embedding for Firefox

When embedding a font, Firefox do not allow you to embed from an external website. Using the .htaccess snippet below, you can bypass this limitation.

<FilesMatch "\.(ttf|otf|eot|woff)$">
<IfModule mod_headers.c>    
    Header set Access-Control-Allow-Origin "http://yourdomain.com"
</IfModule>
</FilesMatch>

Source: http://snipplr.com/view/53703

Speed up your site with .htaccess caching

This is probably the most useful snippet of this whole list. By using some simple .htaccess file cahing, you can dramatically increase your website speed. A snippet you should always have on your toolbox!

# 1 YEAR
<FilesMatch "\.(ico|pdf|flv)$">
Header set Cache-Control "max-age=29030400, public"
</FilesMatch>
# 1 WEEK
<FilesMatch "\.(jpg|jpeg|png|gif|swf)$">
Header set Cache-Control "max-age=604800, public"
</FilesMatch>
# 2 DAYS
<FilesMatch "\.(xml|txt|css|js)$">
Header set Cache-Control "max-age=172800, proxy-revalidate"
</FilesMatch>
# 1 MIN
<FilesMatch "\.(html|htm|php)$">
Header set Cache-Control "max-age=60, private, proxy-revalidate"
</FilesMatch>

Source: http://www.askapache.com/htaccess/speed-up-sites-with-htaccess-caching.html

Stop spam on your WordPress blog

Sick of spammers on your WordPress blog? Of course, Akismet helps a lot, but your .htaccess file can also help: Today’s recipe is a snippet that prevent spam bots to directly access your wp-comments-post.php file, which is used to post comments on your blog.

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_METHOD} POST
RewriteCond %{REQUEST_URI} .wp-comments-post\.php*
RewriteCond %{HTTP_REFERER} !.*yourdomainname.* [OR]
RewriteCond %{HTTP_USER_AGENT} ^$
RewriteRule (.*) ^http://%{REMOTE_ADDR}/$ [R=301,L]
</IfModule>

Source: http://www.wprecipes.com/reduce-spam-on-your-wordpress-blog-by-using-htaccess

Redirect different feeds to a single format

Years ago, differents feed formats, such as RSS, Atom or Rdf were used. Nowadays, it seems that RSS is definitely the most used. This snippets allows you to redirect all feeds formats to a single feed. This snippet can be used “as it” on WordPress blogs.

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

Source: http://www.wprecipes.com/redirect-feeds-to-a-single-format

Configure your website for HTML5 videos

HTML5 is bringing lots of new exiting options in the world of web development. Among other cool features, being able to play videos without using Flash is really cool. Though, you have to configure your server properly to work with the latest HTML5 video standards. This snippet will definitely help.

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !=/favicon.ico
AddType video/ogg .ogv
AddType video/ogg .ogg
AddType video/mp4 .mp4
AddType video/webm .webm
AddType application/x-shockwave-flash swf

Source: http://snipplr.com/view.php?codeview&id=53437

Log PHP errors

Instead of displaying PHP errors to your site (and to possible hackers…) this code snippet will log it into a .log file while hiding errors to visitors.

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

Run PHP inside JavaScript files

When coding in JavaScript, it can very useful to be able to use PHP inside the .js files, for example for retrieving data from your database. Here is a snippet to allow the use of PHP inside .js files.

AddType application/x-httpd-php .js
AddHandler x-httpd-php5 .js

<FilesMatch "\.(js|php)$">
SetHandler application/x-httpd-php
</FilesMatch>

Source: http://www.kavoir.com/2010/07/how-to-execute-run-php-code-inside-javascript-files.html

  • Odt

    .htaccess caching is super useful. Just tried it out on a simple app and it was loading a ton faster. Thanks for sharing these.

  • David

    Some interesting snippets – might want to proofread and spellcheck your posts before you publish, though.

    • Paola

      Would you prefer if he was writing in French then? I’m sure he wouldn’t make any mistakes in his own language.

  • http://www.homeguide.gr/ Giannis

    Is there a big difference if you use .htaccess caching instead of using a caching plugin in WP? I mean, does it affect a lot server load?

  • http://joaocunha.eti.br João Cunha

    Don’t quite understand how the anti-bot snippet would work, since its easy for spammers to fake the HTTP_REFERER. Does the .htaccess file identify the access origin differently than PHP?

  • http://cajebo.com Michael

    Hello Jean-Baptiste! Thanks again for completely usable tips/tricks. I’d almost forgotten the one about prevention of hotlinking!

    Here’s a bonus question for you— how might you code an htaccess snippet to allow for redirection of a post/page URL?

    For example, if you were doing a real estate site, and named a post 123 Main Street
    If using the /%postname%/ for permalinks, URL for that would of course be restatesite.com/123-main-street.com

    Now, how to write htaccess snippet that allowed for user to put in 123mainstreet.realestate.com Granted, one would need to change the slug for the post to be 123mainstreet, but what sort of htaccess code would you put for moving that ‘before the first “dot”, adding a trailing slash to the URL, and then transposing it.

    Again, I’ve seen this snippet somewhere but can’t seem to find it again.
    I imagine however that this would be a piece of cake for you! :)

    Thanks again for everything you post here.

  • http://www.joydeepdeb.com/ Joydeep

    These tips are really useful, I will try them. Thanks for sharing Jean.

    Few tips from my end –
    //Prevent directory listings
    Options All -Indexes

    //Prevent viewing of .htaccess file

    order allow,deny
    deny from all

    //Set Custom 404 errors
    ErrorDocument 404 /error-404.html

    //Redirect from Non-WWW to WWW version
    Options +FollowSymLinks
    RewriteEngine on
    RewriteCond %{HTTP_HOST} ^example.com[nc]
    RewriteRule ^(.*)$ http://www.example.com/$1 [r=301,nc]

  • http://www.themanagementskills.com Rashid Rupani

    Interesting piece of information. Caching and hot-linking snippet is very useful…

  • James Hardy

    Number 3 (Redirect mobile devices) could cause annoying problems for users. (see http://www.xkcd.com/869/ for a good reason why)

    A better solution would be to redirect to an interstitial, that said:

    Our website is not currently optimised for mobile browsers. We have a mobile site that you may wish to visit instead
    [Use Mobile site] [Continue to requested page]

    Use mobile site is just a link to /m/ (or wherever), and continue to requested page is a script which sets a cookie “useFullSite” and redirects them to the original URL.

    then change the last line of the rewrite to
    RewriteCond %{HTTP_COOKIE} !^.*useFullSite.*$
    RewriteRule ^(.*)$ /mobilechoice.php?url=$1 [L,R=302]

  • http://www.weingut-fuchs.de Hildegard Fuchs

    Hotlinking:
    For some people are allowed to use our images, we use a “black list” for hotlinkers:
    RewriteCond %{HTTP_REFERER} ^http://first_hotlinker.com/.*$ [NC,OR]
    RewriteCond %{HTTP_REFERER} ^http://www.last_hotlinker.com/.*$ [NC]
    RewriteRule \.(gif|jpg|jpeg)$ do-not-hotlink.png [R,L]
    Of course you can also use the opposite as a “white list” instead.

  • Davey

    I really like the mobile phone recognition code. I would say though, that nice as is to use responsive design, it’s not enough on it’s own to give mobile users a better experience. If I’m on a phone, and paying for data, I want a very narrow selection of information, especially if I’m using something like a newspaper site.

    Also relative to newspaper sites, there will be a ton of inline images. CSS alone is no good here, you have to deliver smaller images too.

    The AddType for videos is nice too.

  • http://linux.bihlman.com/ Fred

    .htaccess is a very powerful, awesome, and not-often-enough used resource for serious web professionals. Thanks!

  • http://www.danielochoa.info Daniel Ochoa

    Very useful htaccess snippets, thanks!

  • http://www.100webhosting.com Jasmine

    Awesome. Htaccess commands and scripts is an art I have yet to fully understand… it actually looks more difficult than PHP… but your snippets definitely make learning much easier! Great snippets!

  • http://twitter.com/mark_up Mark Simpson

    Can’t count to 11?

  • http://www.webdeveloperblog.co.uk Jamie Murphy

    Great article and some extremely useful snippets in there! One or two have been added to my collection! Thank you!

  • http://www.starac.hr Alen Yacht

    Does this simple PHP caching means that users will not see any changes in php files before one minute is expired?
    That would make it pretty useless for dynamic sites like forums…

  • http://cobases.com Michael Evan

    So far I was familiar with redirects that were done via .htaccess file and some optimization to store proper error logs but didn’t know that it’s possible to avoid spam bots from accessing your site. Will try this about on few of my blogs that gets hundreds of spam comments on daily bases.

  • http://mmovz.com/ Daniel

    I’d love to use the snippet “Speed up your site with .htaccess caching”, but my web hoster doesn’t allow the Apache module mod_expires.c and therefore it won’t work…

  • http://www.webdesigntaiwan.com David

    Nice – .htaccess caching – now that’s also a nice little tip for ‘Page Speed’ and it’s relevance to SEO now that Google puts more weight on it.

    Thanks,
    David

  • http://ukwebsolutionsdirect.co.uk Paul

    Not sure if the Force trailing slash will help for SEO, unless someone here wants to chip in how, but the .htaccess cache settings will for sure, Google likes fast loading sites and those caching techniques work a treat.

  • http://blogsnewsreviews.com Astro Gremlin

    The htaccess cacheing snippet looks very useful. Wanted to say thanks before checking out the article.

  • Carlos

    Thank you so much.
    I finally found the “Add trailing slash” snippet that really DOES work.
    I will love you for all eternity,

  • http://www.agigsm.com/ Theodore Medel

    I’m just unhappy I can just “thumbs-up” your post just once.

  • http://www.tospitakimou.gr Chris

    Have cached my .htaccess about a month ago and already have great results on my page speed. Cool tutorial, thanks a lot !

  • http://www.thehomelovers.com Alex P.

    Hmm… still no results in my case though i followed the tut step by step. Anyone can help ??