views:

13960

answers:

6

I would like to redirect www.example.com to example.com.

The following htaccess code makes this happen:

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

But, is there a way to do this in a generic fashion without specifying the domain name?

A: 

Try this:

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

If the host starts with www, we stick the whole host onto the start of the URL, then take off the "www."

Greg
RoBorg, unfortunately your settings don't work, if I try this:http://www.example.com/hello/worldI end up here:http://example.com/hello/world/worldI also had to add a slash after %{HTTP_POST} in the First RewriteRule
deepwell
It works fine for me (on Apache 2)
Greg
I'm using Apache/2.2.9 (Unix).It works for www.website, which redirects to websiteBut for the following:http://www.website/test -> goes to: http://www.websitetest/I fixed this by adding another /Second error:http://www.website/test/n goes to http://www.websitetest/n/n
deepwell
A: 
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^/(.*)$ http://%1/$1 [R]

The RewriteCond captures everything in the HTTP_HOST variable after the "www." and saves it in %1. The RewriteRule captures the URL (sans leading "/") and saves it in $1.

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

Same as Michael's except this one works :P

If it does not work, you are probably missing the `RewriteEngine On` precursor to make it work.
hendry
+1  A: 

Please see here:

http://no-www.org/

They've got code samples for apache.

Gabriel Hurley
+1  A: 

But if we need to do this for separate http and https:

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

  RewriteCond %{HTTPS} on
  RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
  RewriteRule ^(.*)$ https://%1/$1 [R=301,L]
Andron
A: 

What about subdomain like http://article.ourtoday.info

I try many times but it's not work !

beBest