Wordpress, Htaccess and Mod Rewrite
A while ago I was wrapping my head around the intricacies of mod_rewrite, especially as it relates to WordPress. I’ve gotta say, it took me a long time to find the information that I needed, so here’s the info that I would have liked, to maybe save you some trouble.
It all started because I was looking for an easy and simple (i.e. one that I can understand) way to automatically redirect any requests for “www.petercoughlin.com” to just “petercoughlin.com”.
Why? Well, it was all about trying to avoid duplicate content. There are plenty of great articles out there explaining duplicate content and why it’s not good, so I won’t go over it here. True, the search engines are getting better at it, but they’re not there yet.
To be fair, this isn’t just about WordPress — it applies to any website, so what I ended up looking at was how to do this with an htaccess file.
In short, you can place certain conditions and rules in your htaccess file, and these rules are processed whenever any page on your website is served up.
So, in my case I wanted to intercept all requests for “http://www.petercoughlin.com/whatever.html” and redirect them to “http://petercoughlin.com/whatever.html”. In other words, just strip the “www.” off the front. Here’s the condition and rule that needed to go in my htaccess file to make it happen;
RewriteCond %{HTTP_HOST} ^www\. [NC]
RewriteRule ^(.*)$ http://petercoughlin.com/$1 [R=301,L]
I know, it looks like gobbledygook, but here’s what it means. The first line is a condition, which uses {HTTP_HOST} to pick up the domain name of the request, and uses ^www\. to check whether it starts with “www.”
The second line uses ^(.*)$ to pick up everything after the domain name and drop it on the end of http://petercoughlin.com
The end result is that any page requests that begin with “http://www.petercoughlin.com” are automatically changed into page requests that begin with http://petercoughlin.com, no matter what page is being requested. How cool is that?
This means that fairly soon there’ll be no more pages beginning with http://www.petercoughlin.com in the search engines. Awesome.
By the way, if you use this bit of code in your htaccess file, don’t forget to change the “petercoughlin.com” bit to your own domain name :-)
del.icio.us
Digg
Propeller
StumbleUpon
Reddit
Furl
My name is Peter Coughlin. I am a freelance developer living in the UK and at the moment I am specialising in WordPress customisation.
0 Responses so far ↓
Go on, leave a comment...
Note: your comments may need to be approved before they are shown.