1

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.
vaindil
  • 7,536
  • 21
  • 68
  • 127

1 Answers1

3

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
    
kums
  • 2,661
  • 2
  • 13
  • 16
  • Oh jeez, I didn't think to check if `mod_rewrite` was enabled! Always the simple things. Your code now works to remove the `www` from the beginning of the URL, but it adds two `/`s to the end: both `https://domain.com` and `https://www.domain.com` redirect to `https://domain.com//`. I would like for it to not add a trailing slash at all (unless there's a reason a trailing slash *should* be added, in which case I'm fine with it). I tried figuring out the regex involved but I'm lost. – vaindil Nov 11 '14 at 18:16