Forum Moderators: phranque

Message Too Old, No Replies

redirecting ww , ww.w , w to www

         

asher02

9:11 pm on Jun 5, 2012 (gmt 0)

10+ Year Member



g1smd, I moved here for a solution.

Im trying to redirect ww.example , ww.w.example and w.example and any variation including non-www to www.example

The simple code for redirecting non-www to www will not work:
RewriteCond %{HTTP_HOST} ^example.com 
RewriteRule (.*) http://www.example.com/$1 [R=301,L]


The second code I test will add www to the domain but it gets worse as www.w.example.com

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


So I came up with a solution until I find a wise one who answer my question just to redirect all version one by one.

RewriteCond %{HTTP_HOST} ^example.com 
RewriteRule (.*) http://www.example.com/$1 [R=301,L]

RewriteCond %{HTTP_HOST} ^w.example.com
RewriteRule (.*) http://www.example.com/$1 [R=301,L]

RewriteCond %{HTTP_HOST} ^ww.w.example.com
RewriteRule (.*) http://www.example.com/$1 [R=301,L]

RewriteCond %{HTTP_HOST} ^ww.example.com
RewriteRule (.*) http://www.example.com/$1 [R=301,L]


This is working but my htaccess file looks like a battle field, Any help will be appreciated.

[edited by: asher02 at 9:27 pm (utc) on Jun 5, 2012]

g1smd

9:25 pm on Jun 5, 2012 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



The clue was in the original answer. :)

Redirect everything other than hostname request for
www.example.com
to
www.example.com


The ! operator is used for "NOT".

asher02

9:38 pm on Jun 5, 2012 (gmt 0)

10+ Year Member



opps, well its 00:35 here brain function is aprox 10% :)

What I did is:
RewriteCond %{HTTP_HOST} !www.example.com 
RewriteRule (.*) http://www.example.com/$1 [R=301,L]


it seems to work , did I miss something or is it valid?

g1smd

9:46 pm on Jun 5, 2012 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



Escape literal periods in RegEx patterns.

Add the $ end anchoring. You want not "exactly" www.example.com rather than "doesn't begin" www.example.com.

Your original pattern would not have redirected requests for www.example.com:80 etc.

RewriteCond %{HTTP_HOST} !^(www\.example\.com)?$
RewriteRule (.*) http://www.example.com/$1 [R=301,L]


The ( ) ? construct stops an infinite redirect loop for pure HTTP/1.1 requests where the host header isn't sent.

asher02

9:52 pm on Jun 5, 2012 (gmt 0)

10+ Year Member



Much appreciated g1smd, Its working great. Time to meet my pillow:)