Forum Moderators: phranque

Message Too Old, No Replies

Redirect subdomains that do not exist to www

Redirect subdomains that do not exist to www

         

VaBeachKevin

7:02 pm on Apr 14, 2010 (gmt 0)

10+ Year Member



I'm having a hard time figuring out this redirect. What I'm trying to do is redirect all subdomains to the www subdomain. Even if they do not exist, I want to redirect them all. If someone comes to my site and types in jksnviruvbqiunbq.example.com I want them to get redirected to www.example.com. Anyone know how I can do this in htaccess?

dmwaff

7:49 pm on Apr 14, 2010 (gmt 0)

10+ Year Member



They can't get your site without a known IP or DNS lookup. Therefore, the jksnviruvbqiunbq.example.com hostname needs to resolve to your HTTP Server first. They don't go to your site and then type jksnviruvbqiunbq.example.com.

When a request comes in you can eval the Host: header and if not www.example.com redirect.

Something like this with mod_rewrite loaded.


RewriteCond %{HTTP_HOST} !^www\.example\.com$ [NC]
RewriteRule . http://www.example.com%{REQUEST_URI} [R,L]

R flag not required due to implied http:// in rule but is good practice for visual reading.

dmwaff

jdMorgan

10:51 pm on Apr 14, 2010 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



The flag should be [R=301,L] to force a 301-Moved Permanently redirect for domain canonicalization in search engines listings.

Also, for use in .htaccess, use a pattern of just "^" because otherwise the URL-path for the root directory won't be recognized -- RewriteRule will see the URL-path as blank if just <any-subdomain>.example.com/ is requested.

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

Jim

jdMorgan

12:00 am on Apr 15, 2010 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



... and as previously-stated, this only works if you have set up a "wild-card" subdomain DNS record to point all possible subdomains to your server, and if your server is configured to recognize requests for all possible subdomains.

Jim