Leave a comment

20+ .htaccess Hacks Every Web Developer Should Know About

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.

1 Options +FollowSymlinks
2 #Protect against hotlinking
3 RewriteEngine On
4 RewriteCond %{HTTP_REFERER} !^$
5 RewriteCond %{HTTP_REFERER} !^http://(www.)?domainname.com/ [nc]
6 RewriteRule .*.(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
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="">
10 Order Allow,Deny
11 Allow from all
12 Deny 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:

1 ErrorDocument 403 http://www.domainname.com
2 Order deny,allow
3 Deny from all
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:

1 Redirect 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:

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:

1 allow from all
2 deny from 145.186.14.122
3 deny 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.

1 ServerSignature EMail
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
2 <files .htaccess="">
3 order allow,deny
4 deny 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)$"="">
3 SetOutputFilter 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)$"="">
2 Header 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
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
02 <files secure.php="">
03 AuthType Basic
04 AuthName "Prompt"
05 AuthUserFile /home/path/.htpasswd
06 Require valid-user
07 </files>
08
09 # password-protect a directory
10 resides
11 AuthType basic
12 AuthName "This directory is protected"
13 AuthUserFile /home/path/.htpasswd
14 AuthGroupFile /dev/null
15 Require 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
2 RewriteEngine On
3 RewriteRule ^(.*)$ 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).

1 FileETag MTime Size
2 ExpiresActive on
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
4
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.

1 RewriteRule ^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:

1 Options 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="">
3 RewriteEngine on
4 RewriteCond %{HTTP_USER_AGENT} !FeedBurner    [NC]
5 RewriteCond %{HTTP_USER_AGENT} !FeedValidator [NC]
6 RewriteRule ^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).

1 RewriteEngine On
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]

Source: How to: Deny comment posting to no referrer requests

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.

1 #remove www from URI
2 RewriteEngine On
3 RewriteCond %{HTTP_HOST} ^www\.domain\.com$ [NC]
4 RewriteRule ^(.*)$ 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
2 RewriteBase /
3 RewriteCond %{REQUEST_FILENAME} !-f
4 RewriteCond %{REQUEST_URI} !#
5 RewriteCond %{REQUEST_URI} !(.*)/$
6 RewriteRule ^(.*)$ 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
2 RewriteCond %{HTTP_HOST} ^www\.example\.com [NC]
3 RewriteRule (.*) http://example.com/$1 [R=301,L]

See Original

Leave a comment