7

I've had some users trying to access a site that is registered as subdomain.example.com with www.subdomain.example.com.

is there some sort of .htaccess rule I can add to redirect people that arrive using www.subdomain.example.com to subdomain.example.com?

Also, do I have to change DNS stuff?

abatishchev
  • 98,240
  • 88
  • 296
  • 433
tester
  • 22,441
  • 25
  • 88
  • 128

3 Answers3

16

Sure, use a directive like:

<VirtualHost *:80> 
    ServerName www.subdomain.example.com 
    Redirect permanent / http://subdomain.example.com/ 
</VirtualHost> 

Apache automatically preserves anything after the / when using the Redirect directive, which is a common misconception about why this method won't work (when in fact it does).

Also, yes you will need to change DNS records, because www.subdomain.example.com is a distinct hostname that needs its own A (or CNAME) record to point the browser to an appropriate server in the first place.

Greg Hewgill
  • 951,095
  • 183
  • 1,149
  • 1,285
  • this assumes the OP is using `NameVirtualHost *:80` – Martin May 26 '10 at 01:24
  • @Martin: That's a reasonably safe assumption. If not, then the important part is the `Redirect` directive, not the `VirtualHost` container. – Greg Hewgill May 26 '10 at 01:26
  • The fact that people are already accessing the site using `www.subdomain.domain.com` suggests that that DNS record may already be in place... if so, it doesn't need to be changed. – David Z May 26 '10 at 02:30
4
RewriteCond %{HTTP_HOST} ^www.subdomain.domain.com
RewriteRule (.*) http://subdomain.domain.com/$1 [R=301,L]
Davinel
  • 940
  • 4
  • 10
  • 20
  • 1
    Using the rewrite engine is a pretty heavyweight way to solve this problem. The `Redirect` directive does exactly the same thing. – Greg Hewgill May 26 '10 at 01:22
  • @GregHewgill Agree, and furthermore, this answer won't even work unless it's placed inside a vhost that will match www.subdomain.domain.com (or the default vhost). – Mark E. Haase Mar 19 '14 at 17:39
-1

You need to add a virtual host directive in httpd.conf and Redirect Permament to the correct subdomain and add the additional DNS entry (CNAME is fine)

Geek Num 88
  • 5,264
  • 2
  • 22
  • 35