Most bloggers do not know the power of .htaccess files. A simple tweak in .htaccess files can bring a drastic increase in the blog performance. In this post I will share 20 .htaccess hacks which will improve the security, usability and overall performance of your blog.

What is .htaccess?

The Wikipedia definition of .htaccess goes like this:
In several web servers (most commonly Apache), .htaccess (hypertext access) is the default name of a directory-level configuration file that allows for decentralized management of web server configuration. The .htaccess file is placed inside the web tree, and is able to override a subset of the server’s global configuration; the extent of this subset is defined by the web server administrator. The original purpose of .htaccess was to allow per-directory access control (e.g. requiring a password to access the content), hence the name. Nowadays .htaccess can override many other configuration settings, mostly related to content control, e.g. content type and character set, CGI handlers, etc.

Simply .htaccess files are invisible plain text files where one can store server directives. Server directives are anything you might put in an Apache config file (httpd.conf) or even a php.ini**, but unlike those “master” directive files, these .htaccess directives apply only to the folder in which the .htaccess file resides, and all the folders inside.

When a .htaccess file is placed in a directory which is in turn ‘loaded via the Apache Web Server’, then the .htaccess file is detected and executed by the Apache Web Server software. These .htaccess files can be used to alter the configuration of the Apache Web Server software to enable/disable additional functionality and features that the Apache Web Server software has to offer. These facilities include basic redirect functionality, for instance if a 404 file not found error occurs, or for more advanced functions such as content password protection or image hot link prevention.

1. Limit WordPress Admin access by IP address.

This method allows wp-Admin folder to be accessed from a particular set of IP addresses and all others will get a forbidden error message. If you access your blog from one or two computers regularly then this method will be very effective. Create a new .htaccess file in wp-admin folder and add the following piece of code into it.
order deny, allow
deny from all
allow from
XXX.XXX.XXX.X

Replace all those X’s with your IP address. You can obtain your IP address from websites like whatismyip.org
Note that this method may not work for everyone. Some ISP’s will provide dynamic IP’s instead of static IP’s for its users. As a result the IP address may get changed each time you connect to the internet. This may lock out you from your admin area. If such a situation occurred then use your FTP to browse to your wp-admin folder and delete the .htaccess file.

2. Set a Custom 404 Page

You can set your own 404 page error page with a small tweak in the .htaccess file. Add the following code to the .htaccess file. Change ‘/error.html’ and add the path to your custom 404 page.

ErrorDocument 404 /error.html

3. Banning a WordPress Spammer With .htaccess

If you ask me what is the most annoying thing for me on the internet then I will answer – Spammers. Sometimes I become mad seeing the spamming activities. This blog is a newer one yet receives around 40 – 50 spam comments daily. If you check the IP addresses form which these comments are originating then you can find that most of them come from some particular IP addresses. If you can block that particular IP addresses from accessing your blog then it will be very good isn’t it? Adding the following snippet of code to your .htaccess files will protect you from person/ bot access from any particular IP address.

order allow,deny
deny from xxx.xx.xxx.xxx
allow from all


Replace xxx.xx.xxx.xxx with the IP address of the spammer. If you do some bit of searching in the internet then you can find lists of IP addresses of the frequent spammers in the cyber world. Learn more about this The easiest way to protect your blog from spammers.

4. Force Caching with htaccess:

The following htaccess code won’t help the initial page load, but it will significantly help subsequent page loads by sending 304 status when requested elements haven’t been modified.

FileETag MTime Size
ExpiresActive on
ExpiresDefault “access plus x seconds”


You can also set different expirations for each file type by breaking each file type up into separate ExpiresByType lines such as:

ExpiresByType image/gif “access plus x seconds”
ExpiresByType text/css “access plus x seconds”


Replace x with the number of seconds, for setting cache for 1 second set x as 86400 seconds.

5. Protect Wp-config.php file:

The wp-config.php file contains sensitive information’s like your database username, password etc. You can edit the .htaccess files to protect config file from unauthorized access. Add the following code snippet into your .htaccess file.

# protect wpconfig.php
<files wp-config.php>
order allow, deny
deny from all
</files>

6. Remove /category/ from the WordPress URL:

By default the category URL’s in WordPress are shown in the following way.

http://www.yourdomain.com/category/wordpress
http://www.yourdomain.com/category/blogging

You can see that the ‘/category/’ in the links is useless. We can remove this with a simple tweak in .htaccess file. Add the following code snippet to the .htaccess file.

RewriteRule ^category/(.+)$ http://www.yourblog.com/$1 [R=301,L]
Once saved, your categories pages will be displayed like this:
http://www.yourdomain.com/wordpress

Learn more about this hack How to remove category from your WordPress URL

7. Protect Directories from Public Browsing:

In many cases, the default WordPress installation allows hackers to use their browser as a file browser to look through the contents of the folders on your server. There is a potential problem letting people know what plugins you have, or what versions they are. If there is some known exploit that is linked to a plugin, it could be easy enough for someone to use it to their advantage.

You can block visitors from browsing the directories by adding the following line to the htaccess file in the directory you’d like to block:

Options All -Indexes

8. Redirect WordPress RSS feed to FeedBurner with .htaccess

I am sure that most of the blogger uses FeedBurner for handling their blog’s RSS feeds. Redirection of the feeds to FeedBurner requires the editing of the theme files or the use of plugins. But there is a simple way to redirect your feeds with the help of .htaccess file. Add the following lines of codes to your .htaccess file.
# temp redirect wordpress content feedburner

RewriteEngine on
RewriteCond %{HTTP_USER_AGENT} !FeedBurner [NC]
RewriteCond %{HTTP_USER_AGENT} !FeedValidator [NC]
RewriteRule ^feed/?([_0-9a-z-]+)?/?$ http://feeds2.feedburner.com/yourfeed [R=302,NC,L]

Don’t forget to edit the feed URL in the line 6. If you want to know more about this trick learn it here –How to redirect WordPress RSS feeds to feedburner.

9. Disable Hot Linking

Got trouble with your bandwidth? It is time for disabling hot linking. Addition of the following code to your .htaccess file will disable hot linking and thus protect you from those people who steal your bandwidth.

Hot Linking is the use of a linked object, often an image, from one site into a web page belonging to a second site. The second site is said to have an inline link to the site where the object is located.

#disable hotlinking of images with forbidden or custom image option
RewriteEngine on
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^http://(www\.)?yourdomain.com/.*$ [NC]
#RewriteRule \.(gif|jpg)$ – [F]
RewriteRule \.(gif|jpg)$ http://www.yourdomain.com/stealingisbad.gif [R,L]

10. Compress static data

By making use of Gzip you can compress files in order to make your website load faster.

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

11. Redirect Day and name permalinks to /%postname%/

The default permalink structure in the WordPress contains day and name of the post. This permalink structure is not good in the user and SEO point of view. Most of the bloggers start with /%postname%/ permalink structure. But what if you started with default structure and then after some months decided to change it. Of course you can change permalink structure in WordPress admin area, but what about the backlinks you gathered? This cute trick comes handy in this situation. Adding the following code to your .htaccess file will redirect your links with old permalink structure to the new permalinks.

RedirectMatch 301 /([0-9]+)/([0-9]+)/([0-9]+)/(.*)$ http://www.yourdomain.com/$4

12. Limiting Number of simultaneous connections

To limit the number of simultaneous connections to a directory or your entire site, use the following hack. If you place it in a directory other than the root directory, then it will limit the connections to that directory and its sub-directories only. Placing it in htaccess file of root directory will implement it for entire site.

Syntax:
MaxClients < number-of-connections>
Examples:
MaxClients 40

13. Redirecting your domain.com[non-www] to www.your-domain.com

From a search engine optimization point of view, we will use permanent redirection such that every time a request for non-www domain is made, it’s redirected and returns a status code of 301 [Permanent Redirect].
RewriteEngine On
RewriteCond %{HTTP_HOST} ^YourSite\.com [nc]
RewriteRule (.*) http://www.YourSite.com/$1 [R=301,L]

14. Redirect Visitors to a maintance page

If you are performing some maintance work to your blog it will be nice to send the visitors to a maintance page during that time. We are using a 302 redirection here so don’t worry about search engines indexing our maintance page instead of home page.

RewriteEngine on
RewriteCond %{REQUEST_URI} !/maintenance.html$
RewriteCond %{REMOTE_ADDR} !^123\.123\.123\.123
RewriteRule $ /maintenance.html [R=302
,L]

15. Redirect everyone except specified IP’s

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:

ErrorDocument 403 http://www.yourdomainname.com
Order deny,allow
Deny from all
Allow from xxx.xx.xx.xxx

Replace x’s with the IP address which you want to allow

16. Force files when opening to ‘Save As’

If you are giving something to download and want to force ‘Save As’ instead of opening and streaming then the following hack comes very useful.

AddType application/octet-stream .avi .mpg .mov .pdf .xls .mp4

17. Set the time zone of your server

The hack below lets you set the time zone of the server:

SetEnv TZ America/Indianapolis

18. Set default email address for server admin

By using the following code you can specify the default email address of the server admin.

ServerSignature EMail
SetEnv SERVER_ADMIN default@domain.com

19. Preventing Spam comments from bots

Of course Akismet is there to protect you from spam comments. But if you have some problems with Akismet and looking for an alternative then this .htaccess hack will work for you. Most spam bots come from nowhere. The following code looks for the referrer (The URL from where the page has been called) when the wp-comments-post.php file is accessed. If a referrer exists, and if it is your blog URL, the comment is allowed. Otherwise, the spam bot is redirected and the comment will not be posted.

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

20. CheckSpelling directive

This directive can be useful to auto-correct simple spelling errors in the URL
CheckSpelling On

These are some of the useful .htaccess hacks which can improve the performance of your blog. Have you tried these hacks? Do you know more .htaccess tricks? Please share your responses.

Typical geek, night owl, gadget freak, budding entrepreneur, WordPress & Ruby enthusiast.