Forum Moderators: phranque
example.co.uk
example.org
example.net
someothername.com
(no www)example.com
.... all 301 to:-
www.example.com
At the moment, these are all dealt with under separate rules, like:-
# Redirect non www to www
RewriteCond %{HTTP_HOST} ^example\.com
RewriteRule ^(.*) http://www.example.com/$1 [L,R=301]
Is there any way of encompassing this under one rule? My thought is basically anything that does not begin with "www.example.com" should be 301'd there. That would basically mean that any domain pointing to this server would get 301'd to a single URI.
Based on that idea I tried the following but it didn't work:-
# Redirect everything to to www.example.com
RewriteCond %{HTTP_HOST}!^www\.example\.com
RewriteRule ^(.*) http://www.example.com/$1 [L,R=301]
Is that simply an error in my syntax, or is this not possible?
Thanks!
TJ
The second feature I like to add is a back door for accessing the site if the DNS goes down or the domain expires (gasp!). Here I show an exception to the redirect if the host is requested by its IP address from my home or office PC's IP address:
# Redirect everything to www.example.com
RewriteCond %{HTTP_HOST} .
RewriteCond %{HTTP_HOST}<->%{REMOTE_ADDR} !^your\.host\.ip\.address(:80)?<->(your\.home\.IP\.address¦your\.office\.IP.address)$
RewriteCond %{HTTP_HOST} !^www\.example\.com
RewriteRule (.*) http://www.example.com/$1 [R=301,L]
Another common exception (not shown here) is to bypass the redirect for control panel or stats directories that are set up by the host to always use IP-address access. Again, this only applies if your server has a unique IP address.
The "<->" character sequence has no special meaning. It is simply a unique string used to delineate the boundary between the two variable values, in order to prevent pattern-matching ambiguity.
Replace the broken pipe "¦" character above with a solid pipe character before use; Posting on this forum modifies the pipe character.
Jim
Great config - thanks.
One question - if I put this into httpd.conf, rather than .htaccess, the "/$1" seems to get ignored.
In other words:-
thewrongdomain.com/foo.html
Will get 301'd to:-
www.example.com/foo.html
If this rewrite code is in .htaccess, but it 404's if it's in httpd.conf.
Is there any specific reason why that would be?
Thanks...
Change the rule to either one of the following:
RewriteRule ^/(.*)$ http://www.example.com/$1 [R=301,L]
RewriteRule (.*) http://www.example.com$1 [R=301,L]