Forum Moderators: phranque

Message Too Old, No Replies

One more question about www redirects(!)

I need a generic way without the 'example.com'.

         

rankerous

3:16 am on Jul 7, 2010 (gmt 0)

10+ Year Member



I need a generic way without the 'example.com' to redirect. I need to make a file that is universal so I can upload it to any server. I found a way that should work to make 'www' redirect to non-www without having to mention the domain name and would like to alter it to do the opposite.

Here is the code to redirect 'www to 'non-www':

RewriteEngine On
RewriteCond %{HTTP_HOST} ^www\.(.*) [NC]
RewriteRule ^(.*) [%1...] [R=301,L]

I don't know the proper syntax to make this non-www => www.

Can anybody help me?

Thanks!

g1smd

5:58 am on Jul 7, 2010 (gmt 0)

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



Test for "NOT www" using an additional RewriteCond and the ! NOT operator.

Redirect only if the requested hostname does not begin with www.

jdMorgan

3:24 am on Jul 10, 2010 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member




# Redirect to remove "www." if present, also removing FQDN period and port
RewriteCond %{HTTP_HOST} ^www\.([^.:]+(\.[^.:])+)\.?(:[0-9]+)?$ [NC]
RewriteRule ^(.*)$ http://%1/$1 [R=301,L]
#
# Redirect to add "www." if not present, also removing FQDN period and port
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteCond %{HTTP_HOST} ^([^.:]+(\.[^.:])+)\.?(:[0-9]+)?$
RewriteRule ^(.*)$ http://www.%1/$1 [R=301,L]
#
# Follow-on rule for either variant above (to remove FQDN and port if "www" is already correct)
RewriteCond %{HTTP_HOST} ^([^.:]+(\.[^.:])+)(\.?:[0-9]+|\.)$
RewriteRule ^(.*)$ http://%1/$1 [R=301,L]

Example valid URL with FQDN and port in hostname: http://www.google.com.:80/

Jim

rankerous

4:08 am on Jul 10, 2010 (gmt 0)

10+ Year Member



Thanks for the help!

The first answer gave me an idea and I did a bunch more searching and I found this, which seems to work great:

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

g1smd

11:04 am on Jul 10, 2010 (gmt 0)

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



That rule does not deal with all possible incorrect variations.

The slightly longer code, above your post, does do so.