Forum Moderators: phranque

Message Too Old, No Replies

Sorting out non-www and www when using subdomains

Canonical URLs and subdomains, .htaccess, rewrite

         

elguiri

4:49 pm on Sep 15, 2005 (gmt 0)

10+ Year Member Top Contributors Of The Month



Before anyone asks, no, I still I haven't sat down to teach myself regex.

Here's the problem. When I set up a new site, I typically include in my .htaccess file as a matter of course, the following:


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

That way all requests for http://example.com are sent to http://www.example.com

So far so good.

Now I have a site with subdomains, and I've discovered a problem.

With this code in my .htaccess file a request for, say, [subdomain.example.com...] is sent, logically, to http://www.example.com/subdomain/

Can anyone help me out with the right rewrite rule for this scenario?

Thanks.

jdMorgan

7:41 pm on Sep 15, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



You have two choices, depending on your plans for this domain -- specifically, depending on how many subdomains you might wish to define for the domain:

You can either use a positive-match RewriteCond to redirect example.com to www.example.com, thus avoiding any redirection of the subdomain, or you can add an exclusion to the negative-match ruleset that you are using now. You'd do this by simply *adding* another RewriteCond identical to the one you have now, but specifying the new subdomain as a negative match against HTTP_HOST.

The first method makes more sense if you plan to add many additional subdomains. If not, either approach should be fine.

The code for both of these methods has been posted many times here, so there's no need to re-post it. A search for "www non-www domain redirect rewriterule [google.com]" will turn up dozens of examples.

Jim

jd01

7:47 pm on Sep 15, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



1st--

This:

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

Should be this:

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

If you do not check to see if the host header is sent, HTTP 1.0 clients will end in a server error, because they do not send host headers.

2nd--

I would start with this thread:
[webmasterworld.com...]

The middle section of Msg. #2 is close to what you will need. (You might also try 'rewrite subdomain to folder site:webmasterworld.com/forum92/' OR 'creating dynamic subdomains site:webmasterworld.com/forum92/' on your favorite SE.)

Justin

elguiri

9:59 am on Sep 16, 2005 (gmt 0)

10+ Year Member Top Contributors Of The Month



Thanks Jim and Justin,

All points noted, and I have it sorted.