AardvarkBusiness.net - Business Search Engine AardvarkBusiness.net - Business Search Engine



 FAQFAQ   SearchSearch   MemberlistMemberlist   UsergroupsUsergroups   RegisterRegister   ProfileProfile   Log in to check your private messagesLog in to check your private messages   Log inLog in 

     

Redirect to www. with mod_rewrite w/out hard coding domain

 
 
Post new topic   Reply to topic    AardvarkBusiness.net Forum Index -> Programming Forum
View previous topic :: View next topic  
Author Message
trev
President
President


Joined: 15 Oct 2002
Posts: 3011
Location: NW England, UK
4037 ants

PostPosted: Fri Sep 04, 2009 3:33 pm    Post subject: Redirect to www. with mod_rewrite w/out hard coding domain Reply with quote

I noticed earlier that a lot of our web sites weren't doing the http://example.com -> http://www.example.com redirect that's often recommended for Google etc. so I set about figuring how to do this.

It's easy if you just have one domain to worry about as there's loads of examples, but they all require you to hard code the domain into mod_rewrite which isn't good when you have 127 sites to update. So after a bit of work I came up with this universal solution.

This will redirect any page on your site to www. version, but can be used on any web site without fiddly domain hard coding or editing:

Code:
RewriteRule .* - [E=thehost:%{HTTP_HOST}]

RewriteCond %{HTTP_HOST} !^www..+$ [NC]
RewriteRule ^(.*)$ http://www.%{ENV:thehost}/$1 [L,R=301]


In essence it works thus:

- Create an environment variable within mod_rewrite / .htaccess to hold the domain.
- Check if the host currently starts with www.
- If not then redirect planting the variable above into the domain bit
-- The $1 just places anything that came after domain.com/xxxx onto the new URL.


Note: I don't know how this would behave if you have sub-domains on your web site as it'd probably require some tweaking to catch those before running this check.

Trev
_________________
Mad Theories - Ambleside - Coniston - Grange
Back to top
View user's profile Send private message Visit poster's website
Display posts from previous:   
Post new topic   Reply to topic    AardvarkBusiness.net Forum Index -> Programming Forum All times are GMT + 1 Hour
Page 1 of 1

 
Google
 
Business Forum Sport Forum Travel Forum


Powered by php B B © 2001, 2002 php B B Group

AardvarkBusiness.net Business Search Engine & Directory