views:

426

answers:

6

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.

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

That should do the trick.

Unkwntech
Attention to ^www.domain.com$: the dots match everything and thus should be escaped. See my answer.
millenomi
This is what I am using on a few websites without fail.
Unkwntech
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
+4  A: 

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
+5  A: 

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
yes...you are the winner for not using mod_rewrite :)
davr
A: 

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
+1  A: 

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
+4  A: 

simpler and easier to copy from site to site:

RewriteCond %{HTTP_HOST} ^www\.(.+)$
RewriteRule ^(.*)$ http://%1/$1 [R=301,L]
This solution is MUCH better than the rest here.
Kendall Hopkins
One important thing to notice about this solution is that it will always forward to HTTP. A better solution might be http://pastebin.com/TjD6iha2
Kendall Hopkins