Tuesday, 14 May 2013

20+ .htaccess Hacks Every Web Developer Should Know About


Apache's .htaccess(hypertext access) configuration file can be a very powerful tool in a web developer's toolkit if used properly. It can be found in the webroot of your server and can be easily edited using any text editor. In this article I'm going to show you 20 .htaccess hacks and how to use them.
Before I start with this article I'd like to start by saying that abusing the .htaccess file will hurt the performance of your website. The .htaccess file should only be used if you have no other way to achieve certain things.
Make sure to back up your current .htaccess file before applying any of the following hacks.

1. Prevent Hotlinking

Tired of people using your bandwidth by putting the images hosted on your server on their website? Add the following code at the bottom of your .htaccess file to prevent hotlinking.
1Options +FollowSymlinks
2#Protect against hotlinking
3RewriteEngine On
4RewriteCond %{HTTP_REFERER} !^$
5RewriteCond %{HTTP_REFERER} !^http://(www.)?domainname.com/ [nc]
6RewriteRule .*.(gif|jpg|png)$http://domainname.com/img/stop_stealing_bandwidth.gif[nc]
NOTE: The following article explains better methods to "prevent" hotlinking:
Link building secrets by Maurizio Petrone

2. Block All Requests From User Agents

It's possible to block all unwanted user agents that might be potentially harmful or perhaps just to keep the server load as low as possible.
01#Block bad bots
02SetEnvIfNoCase user-Agent ^FrontPage [NC,OR]
03SetEnvIfNoCase user-Agent ^Java.* [NC,OR]
04SetEnvIfNoCase user-Agent ^Microsoft.URL [NC,OR]
05SetEnvIfNoCase user-Agent ^MSFrontPage [NC,OR]
06SetEnvIfNoCase user-Agent ^Offline.Explorer [NC,OR]
07SetEnvIfNoCase user-Agent ^[Ww]eb[Bb]andit [NC,OR]
08SetEnvIfNoCase user-Agent ^Zeus [NC]
09<limit get="" post="" head="">
10Order Allow,Deny
11Allow from all
12Deny from env=bad_bot
13</limit>

3. Redirect Everyone Except Specified IPs

If for some reason you would want to deny everyone or allow only a specific group of IP addresses to access your website, add the following code to your .htaccess file:
1ErrorDocument 403 http://www.domainname.com
2Order deny,allow
3Deny from all
4Allow from 123.251.48.165
5Allow from 123.54.221.123

4. SEO Friendly 301 Redirects

If you've transferred domain names or wish to redirect a specific page or pages without getting penalty from search engines such as Google, use the following code:
1Redirect 301 /d/file.html http://www.domainname.com/r/file.html

5. Creating a Custom Error Page

Are you as tired as me of the default layout of 404 error pages? Well now you can easily create your own and refer to it like this:
1ErrorDocument 401 /error/401.php
2ErrorDocument 403 /error/403.php
3ErrorDocument 404 /error/404.php
4ErrorDocument 500 /error/500.php

6. Create an IP Banlist

Tired of getting the same bs comments specific user over and over again? Just ban the bastard like this by adding the following code to your .htaccess file:
1allow from all
2deny from 154.186.14.123
3deny from 124.15

7. Set Default Email Address For Server Admin

Using the following code you can specify the default email address for the server's admin.
1ServerSignature EMail
2SetEnv SERVER_ADMIN default@domain.com

8. Disable Display of Download Request

Usually when downloading something from a web site, you'll be prompted if you wish to open the file or save it on your hard-disk. To prevent the server from prompting users wether they wish to open or save the file and to just save the file, use the following code:
1AddType application/octet-stream .pdf
2AddType application/octet-stream .zip
3AddType application/octet-stream .mov

9. Protect a Specific File

The following code allows you to deny access to any file you wish by throwing an 403 error when it is trying to be accessed. In the following example I've chosen to protect the .htaccess file by adding an extra layer of security.
1#Protect the .htaccess File
2<files .htaccess="">
3order allow,deny
4deny from all
5</files>

10. Compress Components With mod_deflate

As an alternative to compressing files with Gzip, you can use mod_deflate(which is supposively faster). Place the following code at the top of your .htaccess file(tip: you can also add .jpg|.gif|.png|.tiff|.ico mod_deflate those):
1<ifmodule mod_deflate.c="">
2<filesmatch ".(js|css)$"="">
3SetOutputFilter DEFLATE
4</filesmatch>
5</ifmodule>

11. Add Expires Headers

The following code shows you how to add an expiration date on the headers.
1<filesmatch ".(ico|pdf|flv|jpg|jpeg|png|gif|swf)$"="">
2Header set Expires "Wed, 21 May 2010 20:00:00 GMT"
3</filesmatch>

12. Setting the Default Page

You can set the default page of a directory to the page of your choice. For example in this code the default page is set as about.html instead of index.html
1#Serve Alternate Default Index Page
2DirectoryIndex about.html

13. Password Protect Your Directories and Files

You can enable password authentication for any directory or file on your server by using the following code:
01#password-protect a file
02<files secure.php="">
03AuthType Basic
04AuthName "Prompt"
05AuthUserFile /home/path/.htpasswd
06Require valid-user
07</files>
08
09# password-protect a directory
10resides
11AuthType basic
12AuthName "This directory is protected"
13AuthUserFile /home/path/.htpasswd
14AuthGroupFile /dev/null
15Require valid-user

14. Redirect an Old Domain to a New Domain

By using the .htaccess file you can redirect a old domain name to a new domain by adding the following code into the htaccess file. Basically what it does is it will remap the old domain to the new one.
1#Redirect from an old domain to a new domain
2RewriteEngine On
3RewriteRule ^(.*)$ http://www.domainname.com/$1 [R=301,L]

15. Force Caching

The following code will not directly increase the loading speed of your website. What it will do is, load the content of your site faster when the same user revisits your website by sending 304 status when requested components have not been modified. You can change the cache expiry by changing the number of seconds(it's currently set at 1 day).
1FileETag MTime Size
2ExpiresActive on
3ExpiresDefault "access plus 86400 seconds"

16. Compress Components By Enabling Gzip

By making use of Gzip you can compress files in order to make your website load faster.
1AddOutputFilterByType DEFLATE text/html text/plain text/xml application/xml application/xhtml+xml text/javascript text/css application/x-javascript
2BrowserMatch ^Mozilla/4 gzip-only-text/html
3BrowserMatch ^Mozilla/4.0[678] no-gzip
4
5BrowserMatch bMSIE !no-gzip !gzip-only-text/html

17. Remove "category" from a URL

To transform this url: http://yourdomain.com/category/blue to -> http://yourdomain.com/blue, just add the following code at the bottom of your .htaccess file.
1RewriteRule ^category/(.+)$ http://www.yourdomain.com/$1 [R=301,L]

18. Disable Directory Browsing

To prevent people from accessing any directories that might contain valueble information or reveal security weaknesses(e.g. plugin directories of wordpress), add the following code to your .htacess file:
1Options All -Indexes

19. Redirect WordPress Feeds to FeedBurner

The following snippet redirects WordPress' default RSS feed feedburner's feed.
1#Redirect wordpress content feeds to feedburner
2<ifmodule mod_rewrite.c="">
3RewriteEngine on
4RewriteCond %{HTTP_USER_AGENT} !FeedBurner    [NC]
5RewriteCond %{HTTP_USER_AGENT} !FeedValidator [NC]
6RewriteRule ^feed/?([_0-9a-z-]+)?/?$http://feeds.feedburner.com/yourfeed [R=302,NC,L]
7</ifmodule>

20. Deny Comments from No Referrer Requests

The problem is that bots just post comments about how to increase your private parts all naturally to your blogs without coming from any other site. It's like they fall from the sky. This neat hack prevents people from posting if they did not come from somewhere else(they can comment just fine if they came from e.g. google).
1RewriteEngine On
2RewriteCond %{REQUEST_METHOD} POST
3RewriteCond %{REQUEST_URI} .wp-comments-post\.php*
4RewriteCond %{HTTP_REFERER} !.*yourblog.com.* [OR]
5RewriteCond %{HTTP_USER_AGENT} ^$
6RewriteRule (.*) ^http://%{REMOTE_ADDR}/$ [R=301,L]

21. Remove File Extension From URL

Thanks to Kartlos Tchavelachvili for this one. What the following code does is, it removes the .php extension(you can change it to whatever you like e.g. html) in a url. It makes the URL prettier & SEO friendlier.
1RewriteRule ^(([^/]+/)*[^.]+)$ /$1.php [L]

22. Remove www from URL

Thanks to Mahalie for the following 2 .htaccess codes.
If you wish to take out the www from your website's URL and transform it from http://www.example.com into http://example.com, add the following to your .htaccess.
1#remove www from URI
2RewriteEngine On
3RewriteCond %{HTTP_HOST} ^www\.domain\.com$ [NC]
4RewriteRule ^(.*)$ http://domain.com/$1 [L,R=301]

23. Add Trailing Slash to URL

Some search engines remove the trailing slash from urls that look like directories - e.g. Yahoo does it. But - it could result into duplicated content problems when the same page content is accessible under different urls. The following code makes sure there's a slash at the end of your URL:
1#trailing slash enforcement
2RewriteBase /
3RewriteCond %{REQUEST_FILENAME} !-f
4RewriteCond %{REQUEST_URI} !#
5RewriteCond %{REQUEST_URI} !(.*)/$
6RewriteRule ^(.*)$ http://domain.com/$1/ [L,R=301]

24. Remove the www. from your website's URL

Below I've provided a simple htaccess snippet to forcefully remove the "www" from your website's URL.
1# Redirect if www.yourdomain.com to yourdomain.com
2RewriteCond %{HTTP_HOST} ^www\.example\.com [NC]
3RewriteRule (.*) http://example.com/$1 [R=301,L]

The Definitive Guide to Apache mod_rewrite

I highly suggest reading the The Definitive Guide to Apache mod_rewrite if you're interested in knowing more about editing the .htaccess file. If you just want to read one book to get to know all about mod_rewrite, this one is it.



No comments:

Post a Comment