Unleashing .htaccess for WordPress

Unleashing .htaccess for WordPress

After my stint with WordPress branding and WordPress security, it was time to take the plunge into the so-called complex world of .htaccess. Once you are done playing with the WordPress dashboard, plugins and themes then you must take the next big step. Well, let me explain what level of editing I am planning to introduce you to in this article:

Whenever you try to access a category page in your WordPress blog then the URL will look something like:


Personally, I hate the word “category” but this is how WordPress will render a URL, right? Using .htaccess we might just remove “category” and make your URL look a lot more professional. This is just one of the many changes that you can make once you understand your .htaccess file.

Let us get our basics cleared up before we start playing with our .htaccess file.

Unleashing .htaccess for WordPress
Image credit: ptz0n

What is .htaccess?

.htaccess is actually the shortened form of Hypertext Access. It is a configuration file which is designed to control the directory in which it is placed and all the respective sub-directories. It is used by Apache based webservers so as to control most of its own features. With time, you will get accustomed to .htaccess.

NOTE: .htaccess in Windows based hosting is a different story altogether. This article pertains to Linux based hosts only!

.htaccess and Apache

I created the below figure to give you an idea of the relationship that .htaccess shares with Apache. Notice how it sits between WordPress and your webserver (Apache, as they call it.) Please understand that this is a very broad explanation of what happens in actuality, but it should be enough for you to understand the data flow in a real time environment.


Apache, as you see above, goes via .htaccess therefore Apache has to listen to whatever it is told. It is a relationship where .htaccess acts as a shield for Apache where it wouldn’t let a layman touch Apache even when some complex changes are to be made. Therefore, you (the webmaster) can make changes to your data flow and the end results (by editing .htaccess) without touching httpd.conf.

Why not Edit httpd.conf Directly?

Ah! Isn’t that the obvious question after the above explanation? Well, most of us here are using shared hosting in some form or another. This means that one server runs plenty of websites and not just your own website. There might be high chance that the httpd.conf targeting that server might contain information about other websites too. Although there isn’t anything confidential stored in httpd.conf, a hosting company cannot let you edit the same as you might disturb another website. Therefore, .htaccess gives you the chance to edit your part of httpd.conf without touching other site settings. Was I clear?

By now it should be easy to understand the below two scenarios:

  • Everything that your .htaccess can do is possible with httpd.conf file.
  • Everything that is possible with httpd.conf is NOT possible with .htaccess file.

Read this before you edit .htaccess!

Before you start playing with your .htaccess file, I will suggest you to read the below pointers:

  • .htaccess has the ability to lock you out of your domain (including tools like FTP and cPanel) so make sure that you are aware of whatever you are doing.
  • If you are using a text editor that supports word-wrap than I would suggest you to disable word-wrap before you edit your .htaccess in it. Apache might be lenient enough when it comes to confusing characters in .htaccess but sometimes it might act crazy.
  • Avoid redundant codes (two different sets of code doing the same stuff) as this might result in an infinite loop that might lead your website visitor nowhere!
  • Changes to sub-directories can be avoided by placing another .htaccess inside that subdirectory and removing the particular code from that .htaccess.
  • In every code that uses RewriteCond you will notice that the code is wrapped up in between the lines and . This is used to enable Apache’s rewrite engine which is called as mod_rewrite. This might not be required if your Apache has already enabled the same but there is no harm in using the same in your .htaccess.
  • Once you open your .htaccess then there is high probability that you will find some code already present in it. Please do not touch this part of code as it is the default that is required by WordPress permalink structures. I will show the code below for your reference:

In cases where WordPress is installed in the root directory:

# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
# END WordPress

In cases where WordPress is installed in a subdirectory called “blog”:

# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /blog/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /blog/index.php [L]
# END WordPress
  • Try to Test your Changes First in a Sub-Directory.
  • Backup! Do I need to tell you that the working .htaccess file must be backed up before you make any changes to your WordPress environment? Yep! You read that right. Some of the plugins have a habit of switching your .htaccess to default therefore you have to backup your .htaccess to avoid such issues.

Securing the .htaccess

You must secure your .htaccess before you think about using the same to re-model your WordPress setup. The below piece of code will secure your .htaccess from any kind of external access. Also, it takes care of the case sensitive characters in the file name. So, .hTACcesS will also be secured just fine.

<Files ~ "^.*\.([Hh][Tt][Aa])">
 order allow,deny
 deny from all
 satisfy all

Protecting wp-config.php

You can use the above code for protecting any important file in WordPress. Like the below code secures wp-config.php:

<files wp-config.php>
order allow,deny
deny from all

Hide Directories inside the WordPress Installation from Public Viewing

As discussed in previous articles, one can restrict public browsing of WordPress directories by using the below piece of code in the .htaccess file:

Options –Indexes

This will presumably block access to every sub directory present inside the particular directory where you make this change.

Blocking IP Addresses

In case you are aware of any IP address that is creating problems with your network then you can block the same using the below code:

<Limit GET POST>
order allow,deny
deny from xxx.xxx.xxx.xxx
deny from yyy.yyy.yyy.yyy
allow from all

Deny Access to Spam-Bots Leaving Comments

In the case of WordPress wp-comments-post.php file is activated whenever someone leaves a comment. The user’s browser sends a referral line with regard to this activity.

In case spam-bots leave a comment then the wp-comments-post.php file is hit directly and no referral is generated. The below piece of code will detect such spam activity and send the spam-bot back to its origin. It’s more like (almost) creating your own Akismet!

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

Note: In line 4, change yourdomain.com to your blog’s URL without www or any other prefix.

Only your IP accesses wp-admin Folder

wp-admin folder is the core of WordPress and if a hacker gets access to this then your life might just come to an end. In such cases it is suggested to give access to your IP address only for the wp-admin folder. You will have to place your root’s .htaccess file inside the wp-admin folder with the below piece of code appended to it. This will make sure that the changes are applied only inside wp-config directory. Use the below code to get this rolling:

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

Note: You will require a static IP from your ISP for this to work. Also, you can add another line of “allow from” so as to permit another IP address.

Hotlinking Disabled

When another website uses an image hosted on your server directly without uploading the same into their disks then your disk space and bandwidth is consumed. This is called as hotlinking and it must be blocked so as to save your precious disk space.

<IfModule mod_rewrite.c>
RewriteEngine on
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^http(s)?://(www\.)?YourDomain.com [NC]
RewriteCond %{HTTP_REFERER} !^http://(www.)?TrustedDomain.com/.*$ [NC]
RewriteRule \.(jpg|jpeg|png|gif)$ http://YourDomain/images/HotlinkingNotPermitted.gif [NC,R,L]

Note: YourDomain.com must be replaced with your blog’s URL (without www) and TrustedDomain.com is the URL of another website whom you want to permit for hotlinking (optional). Also, http://YourDomain.com/images/HotlinkingNotPermitted.gif is the URL of the image you want to display on the website which is hotlinking to your images. Let them know that you are smarter than them!

Redirect Visitors to Maintenance Page

If you plan to change your blog’s theme or test a new plugin then it is suggested that you redirect your blog’s visitors to a maintenance page. This technique is usually used by webmasters to let their visitors know that website maintenance is in process and the time period of maintenance. The below code will do the task for you:

<IfModule mod_rewrite.c>
RewriteEngine on
RewriteCond %{REQUEST_URI} !/maintenance.html$
RewriteCond %{REMOTE_ADDR} !^123\.456\.789\.000
RewriteRule $ /maintenance.html [R=302,L]

Please be aware that maintenance.html is the page which will be used as your website’s maintenance page. Also, change the numbers in the 3rd line with your IP address so that you aren’t greeted with the maintenance page during the upgrade process.

Use Browser Caching to Improve Blog Speed

A WordPress blog might get a beating from every corner if it loads slowly. This is when the below code comes in handy. It will add cache control headers to your blog which will increase the caching timespan on browsers. This will of course decrease your blog’s load time. The code should be self-explanatory.

<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType image/jpg "access 1 year"
ExpiresByType image/jpeg "access 1 year"
ExpiresByType image/gif "access 1 year"
ExpiresByType image/png "access 1 year"
ExpiresByType text/css "access 1 month"
ExpiresByType application/pdf "access 1 month"
ExpiresByType text/x-javascript "access 1 month"
ExpiresByType application/x-shockwave-flash "access 1 month"
ExpiresByType image/x-icon "access 1 year"
ExpiresDefault "access 2 days"

I tested the above code with my blog CompuWorld and the results were positive. The screenshot below shows the results without browser caching code (using Page Speed for Chrome):

CompuWorld 1

Now, see the increment of one with the browser caching code enabled. It was just one because my blog is pretty fast already!

CompuWorld 2

Just to double check, I tested the same on my other blog Bell The Bull, and the score jumped from 84 to 90. It works, folks!

Removing “/year/month/day/” from Permalinks

You will find multiple versions of this on the Internet and most of them will work just fine. I would request you to use one method and stick to it. Also, please note that you might lose most of your Google Juice and PageRank for the time period when Google is re-indexing your new URLs. Although traffic should be back in 2-3 weeks, PR takes quite some time to recover. Henceforth, bite your tongue if you do not want to take the risk. It isn’t that important actually. After all, TechCrunch uses the same odd lengthy permalinks!

Note: Above SEO based conditions will be considered when we remove /category/ from our permalinks.

For starters, change your permalink structure from:




Now, in your .htaccess look for the default redirect rules in the default WordPress .htaccess code and place the below line above those redirect rules:

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

Remember to change domain.com with your blog’s URL.

Removing /category/ from Permalinks (finally)

As promised, let us remove /category/ from the category based permalinks in WordPress. Paste the below code into your .htaccess file just above the first RewriteRule in the default part of .htaccess code that is used by WordPress. Just for your reference (and to clear any confusion), after you paste the code then this is how the final default code will look like:

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^category/(.+)$ http://mydomain.com/$1 [R=301,L]
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]

If you are looking for ways to setup your own shopping website, trying using an online store builder without trouble in editing the htaccess files.


Well, this was almost everything that you can do with your .htaccess file. I agree that there are lot more changes that one can perform but these were enough for you to consume in one article. Let me know if there were any typos in the codes and what all you all have been using.

Salman Siddiqui is a seasoned WordPress critic with 5 years of WordPress experience. He is an alpha geek with a degree in computer engineering. He spends his day as software engineer with a Fortune 100 company and nights as a freelance writer. He believes that everyone must blog about something and plans to be a full time writer in future.


    • Patrice,
    • November 3, 2011
    / Reply

    Thanks Salman for all these useful tips and very clear explanations !

  1. / Reply

    Is it not possible to combine some of these? eg, add the spam bot section to the original mod_rewrite.c code that’s already in there?

    1. / Reply

      I will suggest that you don’t do so because sometimes too much code inside a set of tags can cause some silly confusion that end up going long way.

  2. / Reply

    I wouldn’t advise changing WP’s permalinks to just /%postname%/ – for reasons of efficiency. If a permalink begins with a numeric section WP_rewrite knows it’s a blog entry and only runs it against posts and other non-hierarchical content. If it’s just /%postname%/ it’ll be checked against every Page rule as well, and WP creates one condition for each slug as opposed to the much more efficient regex for dates.

    1. / Reply

      in that case /%category%/%postname% will also have similar results?

      I have seen most of the large WP based blogs use it and never read about such issues. I will surely be digging more into this..

      • Rob,
      • November 18, 2011
      / Reply

      I’ve read similar, and from a programmers perspective it’s better to have the post id in the path, ie

      That way it’s pretty in terms of SEO and the user. And also fast in terms of fetching the post. If you just use the %postname% wordpress has to do a database lookup via the name which is slower than if it has the Id.

    • Ronald,
    • November 12, 2011
    / Reply

    Very informative article. I am implementing some of these techniques in my .htaccess

  3. / Reply

    Please, if you can tell how to redirect %post_id% to %postname%.html directly will be really helpful in windows sharing envoirment

  4. / Reply

    Awesome info, really helpful will try these things on my blog for sure. Thanks Salman.

  5. / Reply

    Really very helpful and hidden tips to improve blog security as well as improving speed by using less plugins.. cheers !!

  6. / Reply

    so this will work on all browsers …?

  7. / Reply

    nice tips …….

  8. / Reply

    Very useful information. Applying to my blog now.

    • TibiS,
    • October 26, 2012
    / Reply

    Hello. Thanks for useful information, but i can’t find any example of banning an IP to access a permalink. There is only <Files example, but my blog is using permalink and i want to ban IP's from a specific adress. Thank you.

  9. / Reply

    I want to change from




    but when I do that the images which I had uploaded before also gets redirected to only /%postname%/ and breaks my images.

    How to do apply this without affecting images

  10. / Reply

    One of the most ignored methods of keeping your install safe is updating
    your install when updates become available which ensures all of the
    latest patches and fixes are applied to your site.

    • Jonte100,
    • May 1, 2014
    / Reply

    Thank you for all useful tips

    • gaurab,
    • March 16, 2018
    / Reply

    thanks for sharing this, please let me know the latest updates and changes that helps me in doing these thing right now.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.


Iconfinder Coupon Code and Review

Iconfinder offers over 1.5 million beautiful icons for creative professionals to use in websites, apps, and printed publications. Whatever your project, you’re sure to find an icon or icon…

WP Engine Coupon

Considered by many to be the best managed hosting for WordPress out there, WP Engine offers superior technology and customer support in order to keep your WordPress sites secure…

InMotion Hosting Coupon Code

InMotion Hosting has been a top rated CNET hosting company for over 14 years so you know you’ll be getting good service and won’t be risking your hosting company…

SiteGround Coupon: 60% OFF

SiteGround offers a number of hosting solutions and services for including shared hosting, cloud hosting, dedicated servers, reseller hosting, enterprise hosting, and WordPress and Joomla specific hosting.