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.
2 | #Protect against hotlinking |
4 | RewriteCond %{HTTP_REFERER} !^$ |
5 | RewriteCond %{HTTP_REFERER} !^http://(www.)?domainname.com/ [nc] |
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.
02 | SetEnvIfNoCase user-Agent ^FrontPage [NC,OR] |
03 | SetEnvIfNoCase user-Agent ^Java.* [NC,OR] |
04 | SetEnvIfNoCase user-Agent ^Microsoft.URL [NC,OR] |
05 | SetEnvIfNoCase user-Agent ^MSFrontPage [NC,OR] |
06 | SetEnvIfNoCase user-Agent ^Offline.Explorer [NC,OR] |
07 | SetEnvIfNoCase user-Agent ^[Ww]eb[Bb]andit [NC,OR] |
08 | SetEnvIfNoCase user-Agent ^Zeus [NC] |
09 | <limit get= "" post= "" head= "" > |
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:
4 | Allow from 124.34 . 48.165 |
5 | Allow from 102.54 . 68.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:
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:
1 | ErrorDocument 401 /error/ 401 .php |
2 | ErrorDocument 403 /error/ 403 .php |
3 | ErrorDocument 404 /error/ 404 .php |
4 | ErrorDocument 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:
2 | deny from 145.186 . 14.122 |
7. Set Default Email Address For Server Admin
Using the following code you can specify the default email address for the server's admin.
2 | SetEnv 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:
1 | AddType application/octet-stream .pdf |
2 | AddType application/octet-stream .zip |
3 | AddType 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 |
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)$" = "" > |
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)$" = "" > |
2 | Header set Expires "Wed, 21 May 2010 20:00:00 GMT" |
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 |
2 | DirectoryIndex 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 |
05 | AuthUserFile /home/path/.htpasswd |
09 | # password-protect a directory |
12 | AuthName "This directory is protected" |
13 | AuthUserFile /home/path/.htpasswd |
14 | AuthGroupFile /dev/null |
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 |
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).
3 | ExpiresDefault "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.
1 | AddOutputFilterByType DEFLATE text/html text/plain text/xml application/xml application/xhtml+xml text/javascript text/css application/x-javascript |
2 | BrowserMatch ^Mozilla/ 4 gzip-only-text/html |
3 | BrowserMatch ^Mozilla/ 4.0 [ 678 ] no-gzip |
5 | BrowserMatch 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.
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:
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= "" > |
4 | RewriteCond %{HTTP_USER_AGENT} !FeedBurner [NC] |
5 | RewriteCond %{HTTP_USER_AGENT} !FeedValidator [NC] |
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).
2 | RewriteCond %{REQUEST_METHOD} POST |
3 | RewriteCond %{REQUEST_URI} .wp-comments-post\.php* |
4 | RewriteCond %{HTTP_REFERER} !.*yourblog.com.* [OR] |
5 | RewriteCond %{HTTP_USER_AGENT} ^$ |
6 | RewriteRule (.*) ^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.
1 | RewriteRule ^(([^/]+/)*[^.]+)$ /$ 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.
3 | RewriteCond %{HTTP_HOST} ^www\.domain\.com$ [NC] |
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 |
3 | RewriteCond %{REQUEST_FILENAME} !-f |
4 | RewriteCond %{REQUEST_URI} !# |
5 | RewriteCond %{REQUEST_URI} !(.*)/$ |
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 |
2 | RewriteCond %{HTTP_HOST} ^www\.example\.com [NC] |
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.