4

For various reasons, such as cookies, SEO, and to keep things simple, I would like to make apache automatically redirect any requests for http://www.foobar.com/anything to http://foobar.com/anything. The best I could come up with is a mod_rewrite-based monstrosity, is there some easy simple way to tell it "Redirect all requests for domain ABC to XYZ"?

PS: I found this somewhat related question, but it's for IIS and does the opposite of what I want. Also it's still complex.

Community
  • 1
  • 1
davr
  • 18,877
  • 17
  • 76
  • 99

6 Answers6

9

It's as easy as:

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

Adapt host names and IPs as needed :)

TobiX
  • 936
  • 6
  • 17
7

simpler and easier to copy from site to site:

RewriteCond %{HTTP_HOST} ^www\.(.+)$
RewriteRule ^(.*)$ http://%1/$1 [R=301,L]
4

Pretty simple if you use mod_rewrite, as we all do ;)

This is part of the .htaccess from my live website:

RewriteEngine on

# Catches www.infinite-labs.net and redirects to the
# same page on infinite-labs.net to normalize things.

RewriteCond %{HTTP_HOST} ^www\.infinite-labs\.net$
RewriteRule ^(.*)$ http://infinite-labs.net/$1 [R=301,L]
millenomi
  • 6,569
  • 4
  • 31
  • 34
1

Use an .htaccess file with some mod_rewrite rules:

RewriteEngine On
RewriteRule ^www.SERVERNAME(.*) http://SERVERNAME$1 [L,QSA]

I'm not sure I got the syntax right with the $1 there, but it's well documented. L sends a location: header to the browser, and QSA means Query String Append.

Michael
  • 8,446
  • 4
  • 26
  • 36
0

Since you mentioned using mod_rewrite, I'd suggest a simple rule in your .htaccess - doesn't seem monstrous to me :)

RewriteCond %{HTTP_HOST} ^www\.foobar\.com$ [NC]
RewriteRule ^(.*)$ http://foobar.com/$1 [L,R=301]
sirprize
  • 436
  • 1
  • 3
  • 9
-1
RewriteEngine On
RewriteCond %{HTTP_HOST} ^www.domain.com$ [NC]
RewriteRule ^(.*)$ http://domain.com/$1 [R=301,L]

That should do the trick.

UnkwnTech
  • 88,102
  • 65
  • 184
  • 229
  • Attention to ^www.domain.com$: the dots match everything and thus should be escaped. See my answer. – millenomi Sep 17 '08 at 21:51
  • This is what I am using on a few websites without fail. – UnkwnTech Sep 17 '08 at 21:53
  • Yes, it will work without unescaped dots, because the dots also match the dot. There aren't many ways for this to go wrong. But it's just better to escape the dots, because that way you say what you mean. – Peter Stuifzand Sep 17 '08 at 23:00