Search code examples
apachehttp-redirectsslubuntu-server

Redirect www to naked domain


I'm trying to redirect all of my website traffic to my naked domain (looks much cleaner in my opinion), but when Googling I found a LOT of different methods for going about it. I use CloudFlare's free SSL, so I'd like a solution that works both with and without SSL (in case something happens and I disable the SSL or whatever), and I'd preferably like to do this globally (i.e. without a .htaccess file). In case it matters, this is Apache 2.4.10 on Ubuntu Server 14.10.

I found this article, but placing his code (below) into my VirtualHost directive gave the error that is below. The Apache error log doesn't have anything useful. What can I do to fix this problem and make it so the redirect works properly? (If I should be doing this some other way I'm open to that as well; I have access to control my DNS settings and whatnot if needed.)

Code inserted into apache2/sites-available/000-default.conf:

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

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

Error code I receive when restarting Apache:

 * The apache2 configtest failed.
Output of config test was:
AH00526: Syntax error on line 30 of /etc/apache2/sites-enabled/000-default.conf:
Invalid command 'RewriteEngine', perhaps misspelled or defined by a module not included in the server configuration
Action 'configtest' failed.
The Apache error log may have more information.

Solution

  • The rewrite module is not enabled by default.

    1. Enable the rewrite module:

      sudo a2enmod rewrite

    2. change your 000-default.conf to

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

      sudo service apache2 restart