Take the 2-minute tour ×
Webmasters Stack Exchange is a question and answer site for pro webmasters. It's 100% free, no registration required.

I have my web application running on EC2 with Apache. I want to redirect www to non-www. On searching Google, I used this but it leads to redirect loop:

<VirtualHost *:80>
    ServerName www.domain.com
    Redirect 301 / http://domain.com/
</VirtualHost>

I am not using virtual hosts as the server only handles one domain. What can be wrong in above example and How can I do 301 redirect?

P.S. I am trying to avoid using .htaccess.

share|improve this question
    
You say you're not using Vhosts (ie. VirtualHosts) but you are using VirtualHosts?! Presumably you have another <VirtualHost> container for domain.com? –  w3d Jan 16 '13 at 9:57
    
Generally allowing the htaccess file handle the redirect is the best method however I'm not familar doing it with the apache conf file. If you want to avoid the htacess there are many methods that you can use actually within the CMS your using. Wordpress, Joomla, Drupal, and so on all have ways of using non-htaccess redirects from non www to www using plugins. –  bybe Jan 16 '13 at 10:36
    
@w3d I mean that there are no virtualhosts defined. VirtualHost mentioned above is the one I tried but did not work. I am asking for a way which works when there are no virtualhosts defined? –  codecool Jan 16 '13 at 10:42

1 Answer 1

up vote 3 down vote accepted

You have to question some confusion, so I'll talk about ways to do a redirect from www to no-www:

1.Create two VirtualHost for two domains and use 301 redirect:

NameVirtualHost *:80
<VirtualHost *:80>
    ServerName example.com
    DocumentRoot "/path/to/site"
</VirtualHost>
<VirtualHost *:80>
    ServerName www.example.com
    Redirect 301 / http://example.com/
</VirtualHost>

2.Create two VirtualHost for two domains and use .htaccess with redirect-rule:

<VirtualHost *:80>
    ServerName example.com
    DocumentRoot "/path/to/site1"
</VirtualHost>
<VirtualHost *:80>
    ServerName www.example.com
    DocumentRoot "/path/to/site2"
</VirtualHost>

and create /path/to/site2/.htaccess with

Redirect 301 / http://example.com/

3.Create 1 VirtualHost and set redirect in common .htaccess:

<VirtualHost *:80>
    ServerName example.com
    ServerAlias www.example.com
    DocumentRoot "/path/to/site"
</VirtualHost>

create /path/to/site/.htaccess with

RewriteEngine On
RewriteCond %{HTTP_HOST} ^www.example.com$ [NC]
RewriteRule ^(.*)$ http://example.com/$1 [R=301,L]
share|improve this answer
    
Thanks for your detailed answer. I had to add one more line to config file to get 1st way working. After adding NameVirtualHost *:80 it worked fine. –  codecool Jan 27 '13 at 11:23

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.