Subdomain handling + forcing www on only 'example.com'

Using a single web hosting account to host multiple sites

Subdomain handling + forcing www on only 'example.com'

Postby muerr » Sun Nov 23, 2008 7:35 pm

I am new to mod_rewrite and I'm working with an existing set of conditions/rules.

I'm trying to meet a customer requirement to allow subdomains in the URL but also rewrite example.com to www.example.com.

The following works, but it doesn't rewrite "example.com" to "www.example.com". I'm not sure how to handle that.

Code: Select all
RewriteCond %{DOCUMENT_ROOT}/%{REQUEST_FILENAME} !-f
RewriteCond %{HTTP_HOST}   !^www.example.com [NC]
RewriteCond %{HTTP_HOST}   !^$
RewriteCond %{HTTP_HOST}   !^localhost [NC]
RewriteCond %{HTTP_HOST}   !^127\.0\.0\.1 [NC]
RewriteCond %{HTTP_HOST}   !^server_hostname.example.com [NC]
RewriteCond %{HTTP_HOST}   !^server_hostname [NC]
RewriteCond %{HTTP_HOST}   ^(www)?([a-z0-9-]).example.com [NC]
RewriteRule ^/(.*)         %2.example.com/$1 [L,R=301]
muerr
 
Posts: 1
Joined: Sun Nov 23, 2008 7:11 pm

Postby richardk » Mon Nov 24, 2008 12:59 pm

Try
Code: Select all
Options +FollowSymLinks

RewriteEngine On

RewriteCond %{DOCUMENT_ROOT}/%{REQUEST_FILENAME} !-f
RewriteCond %{HTTP_HOST} !^(www|server_hostname)\.example\.com$ [NC]
RewriteCond %{HTTP_HOST} !^(localhost|127\.0\.0\.1)?$ [NC]
RewriteCond %{HTTP_HOST} !^server_hostname [NC]
RewriteCond %{HTTP_HOST}/www ^example\.com(/)(www)$ [NC,OR]
RewriteCond %{HTTP_HOST} ^(www\.)?([a-z0-9-])\.example\.com$ [NC]
RewriteRule ^/(.*)$ http://%2.example.com/$1 [R=301,L]
richardk
 
Posts: 8800
Joined: Wed Dec 21, 2005 7:50 am

Postby ewel » Thu May 14, 2009 1:00 pm

I did it by using the common examples found on the web and skipping the www requirement if the subdomain condition is met, using s=1. It seems to work.

Code: Select all
########## Begin - Require www and subdomain
#
# no subdomain
RewriteCond %{REQUEST_URI} !^/robots\.txt$
RewriteCond %{HTTP_HOST} \.([a-z-]+\.[a-z]{2,6})$ [NC]
RewriteRule ^/(.*)$ http://%1/$1 [R=301,s=1]
#
# www
RewriteCond %{REQUEST_URI} !^/robots\.txt$ [NC]
RewriteCond %{HTTP_HOST} !^www\.[a-z-]+\.[a-z]{2,6} [NC]
RewriteCond %{HTTP_HOST} ([a-z-]+\.[a-z]{2,6})$     [NC]
RewriteRule ^/(.*)$ http://%1/$1 [R=301]
#
########## End - Require www and subdomain
ewel
 

Postby richardk » Fri May 15, 2009 8:22 am

That looks overly complicated, what are you trying to achieve?
richardk
 
Posts: 8800
Joined: Wed Dec 21, 2005 7:50 am


Return to Domain Handling

Who is online

Users browsing this forum: No registered users and 3 guests

cron