0

I had set up 2 domain virtualhost files under /etc/apache2/sites-available,

www.example.com.conf
example.com.conf

apart from the default configurations. I've been trying to create a redirection from example.com to www.example.com and it doesn't seem to work, I don't know where I'm going wrong.

In www.example.com.conf

<VirtualHost *:80>
    ServerAdmin webmaster@localhost
    ServerName www.example.com
    DocumentRoot /var/www/project
</VirtualHost>

In example.com.conf

<VirtualHost *:80>
    ServerName example.com
    ServerAdmin admin@mailzak.com
    DocumentRoot /var/www
    Redirect / http://www.example.com/
</VirtualHost>

After adding them, I had configured with "a2ensite" and restarted Apache. But the redirection doesn't work.

  • They had to, your config seems okay. Is apache restart really worked? Try to stop apache, check for any remaining apache process, kill them if they exist, and then restart. – peterh - Reinstate Monica Jan 14 '15 at 10:29
  • Another tip: could you doublecheck, if in /etc/apache2/sites-enabled , both of the soft links to the virtualhosts are existing and they are pointing to the correct file? – peterh - Reinstate Monica Jan 14 '15 at 10:30
  • 1
    Have you verified that (1) the request to example.com is arriving at your server (check /var/log/apache2/access.log), and (2) the VirtualHosts are enabled (try apachectl fullstatus and search the result for VirtualHost)? – Andrew Schulman Jan 14 '15 at 10:33
  • @Peter.. I see the same links on sites-enabled and linked correctly. – Coding active Jan 14 '15 at 10:37
  • This isn't a problem actually, and leaving out the fact that redirecting non www to www shouldn't be handled this way, it's about 2 websites with the same root and it depends on which loads first, try renaming the redirect vhost by adding an a in front (example.conf becomes aexample.conf) re enable and reload apache2 service ... – Alexandru Kiss Jan 14 '15 at 12:32
0

Provided that www is a canonical alias of the naked domain, you don't really need two .conf files.

You only need one .conf file

<VirtualHost *:80>
ServerName example.com
ServerAlias www.example.com
DocumentRoot /var/www/project
</VirtualHost>

Which can be activated with a2ensite example.com.

Then create an .htaccess file in /var/www/project

Options +FollowSymLinks -Multiviews
RewriteEngine on
RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^(.*)$ http://www.example.com/$1 [R=301,L]

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