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:

www.YourDomain.com/category/CategoryName

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.

htaccess

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]
</IfModule>
# 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]
</IfModule>
# 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
</Files>

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
</files>

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
</Limit>

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_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]
</IfModule>

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:

<LIMIT GET>
order allow, deny
deny from all
allow from xx.xx.xx.xx
</LIMIT>

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]
</IfModule>

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]
</IfModule>

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"
</IfModule>

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:

/%year%/%monthnum%/%day%/%postname%/

to:

/%postname%/

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]
</IfModule>

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.

Conclusion

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.

Deals

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.