HTTP to HTTPS redirect not working on Apache 2.4

This is way overcomplicated. You only need two (or three) directives to redirect everything to HTTPS, e.g.

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

This will redirect both with and without www to the canonical HTTPS site.


The other answer already gives the solution, I thought I'd add why your code might not work as intended.

mod_rewrite is enabled

However, mod_rewrite directives in a directory (or .htaccess) context are not inherited by default. (mod_rewrite behaves somewhat differently to other modules in this respect.)

So, if you had a .htaccess file in the /public_html directory that uses mod_rewrite (eg. a default WordPress installation perhaps) then this will completely override the mod_rewrite directives in the parent <Directory> container in the server config. So, your redirect will never happen.

However, if you moved the mod_rewrite directives out of the <Directory> container and directly into the <VirtualHost> container then this might work OK. mod_rewrite directives in a virtual host (or server config) context will execute before .htaccess. For example:

<VirtualHost *:80>
DocumentRoot "/home/example/public_html/"
ServerName www.example.com

RewriteEngine on
RewriteRule ^(.*)$ https://www.example.com/$1 [R=301,L]

<Directory "/home/example/public_html/">
    Require all granted   
</Directory>
</VirtualHost>

Note that this is purely theoretical. You don't need mod_rewrite at all here, use Esa Jokinen's solution instead.

Note also that allow from all is Apache 2.2 syntax. This is deprecated on Apache 2.4 and should be replaced with the equivalent Require directive. See Apache docs - Upgrading to 2.4 from 2.2