0

I have the following set up for my virtual host:

<VirtualHost *:80>
    ServerName www.example.com
    ServerAlias example.com
    DocumentRoot /var/www/example.com
    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined
    RewriteEngine On
    RewriteCond %{HTTPS} Off
    RewriteRule .* https://%{HTTP_HOST}%{REQUEST_URI} [R,L]
</VirtualHost>

This works fine if I visit http://www.example.com or http://example.com. However, if I go to a specific URL like http://www.example.com/docs/ it does not redirect to HTTPS, and will maintain the non-secure connection. Why is this happening?

Ryan Palmer
  • 105
  • 5

1 Answers1

1

Rather than trying to solve what's wrong with the RewriteRule this is a text book case of When not to use mod_rewrite:

To redirect http URLs to https, do the following:

<VirtualHost *:80>
    ServerName www.example.com 
    Redirect "/" "https://www.example.com/"   
</VirtualHost>

Just add the ServerAlias. It's also better to redirect to a canonical name.

Esa Jokinen
  • 46,944
  • 3
  • 83
  • 129
  • Excellent! This usage of `RewriteRule` was automatically generated by `letsencrypt` when I configured the SSL certificate. But this works perfectly and is much cleaner! – Ryan Palmer Sep 19 '18 at 03:52