301 Redirect from www to non-www without using VHOST

8,916

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:
8,916

Related videos on Youtube

codecool
Author by

codecool

Updated on September 18, 2022

Comments

  • codecool
    codecool over 1 year

    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.

    • MrWhite
      MrWhite over 11 years
      You say you're not using Vhosts (ie. VirtualHosts) but you are using VirtualHosts?! Presumably you have another <VirtualHost> container for domain.com?
    • Simon Hayter
      Simon Hayter over 11 years
      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.
    • codecool
      codecool over 11 years
      @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
    codecool about 11 years
    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.