E
E
esin2012-03-06 22:49:00
Apache HTTP Server
esin, 2012-03-06 22:49:00

Redirect from www.example.com to example.com (apache2, ubuntu 10.04)?

Good day to all!
I ran into such a problem - you need to organize a redirect on the site from www.example.com to example.com
Google gave two main pieces of advice: this is mod_rewrite with redirect conditions like

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

Or a direct redirect using virtual hosts like
<VirtualHost *>
  ServerName www.example.com
  Redirect 301 / http://example.com/
</VirtualHost>

The second method does not work for me (firefox gives an error about endless redirects), the first one works, but there is one thing: if I add additional parameters to the main address, for example www.example.com/test_page/ , then no redirect occurs.
Please tell me how to fix?
PS I don't deal with sites myself, I don't want to delve into the syntax of this mod ... Only as a last resort.
Thank you!

Answer the question

In order to leave comments, you need to log in

6 answer(s)
A
Anatoly, 2012-03-06
@esin

One $ character difference in the first line

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

V
vadkuz, 2012-03-07
@vadkuz

in .htaccess
www www if suddenly it doesn't work add over the selected option
RewriteCond %{HTTP_HOST} ^www.domain\.com$ [NC]
RewriteRule ^(.*)$ domain.com/$1 [R=301,L]

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

Options +FollowSymLinks
RewriteEngine On

B
bost84, 2012-03-07
@bost84

If nginx is in front of Apache, then it is better for them to organize a redirect

S
serso, 2012-03-06
@serso

RewriteEngine on
RewriteCond %{HTTP_HOST} !^se\.solovyev\.org$
RewriteRule ^ se.solovyev.org% {REQUEST_URI} [R=301,L]
Github code

A
Alexander Zelenin, 2012-03-07
@zelenin

<IfModule mod_rewrite.c>
RewriteCond %{HTTPS} !=on
RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
RewriteRule ^ %1% {REQUEST_URI} [R=301,L]
here is the smartest option from the boilerplate. Almost the same as in comment n.1

V
Vic Shostak, 2013-12-18
@vikkyshostak

The option I always use:

RewriteEngine On
RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
RewriteRule ^ http%{ENV:protossl}://%1%{REQUEST_URI} [L,R=301]

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question