HTTP to HTTPS redirect not working on Apache 2.4
Solution 1
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.
Solution 2
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
Related videos on Youtube
![Noodles](https://i.stack.imgur.com/1Iivp.jpg?s=256&g=1)
Noodles
Updated on September 18, 2022Comments
-
Noodles almost 2 years
I have this apache config:
<VirtualHost *:80> DocumentRoot "/home/example/public_html/" ServerName www.example.com <Directory "/home/example/public_html/"> allow from all RewriteEngine on RewriteRule ^(.*)$ https://www.example.com/$1 [R=301,L] </Directory> </VirtualHost>
The redirect never seems to fire and just serves files from http. I've tried all sorts of combinations, but nothing seems to work.
mod_rewrite is enabled (using LoadModule rewrite_module modules/mod_rewrite.so)
Can anyone help?
-
Esa Jokinen almost 5 yearsThis will redirect every request beginning with the base URL, as explained in the documentation for mod_alias
Redirect
: "Then any request beginning with URL-path will return a redirect request to the client at the location of the target URL. Additional path information beyond the matched URL-path will be appended to the target URL."