Search code examples
apachehttphttp-redirecthttps

Redirect HTTP to HTTPS on default virtual host without ServerName


On my apache server I'd like to be able to redirect all incoming http requests to the equivalent https request. The catch is that I'd like to be able to do this for my default virtual host without specifying the ServerName and have the redirect work with whatever server name appeared in the request url. I'm hoping for something like this:

NameVirtualHost *:80
<VirtualHost *:80>
    RedirectPermanent / https://%{SERVER_NAME}/
    ...
</VirtualHost>

Is this possible using Redirect or will I have to resort to Rewrite?


Solution

  • Try adding this in your VirtualHost config:

    <VirtualHost *:80>
       ServerName example.com
       RewriteEngine On
       RewriteCond %{HTTPS} off
       RewriteRule ^(.*)$ https://%{HTTP_HOST}/$1 [R=301,L]
    <VirtualHost>