Redirect HTTP to HTTPS for multiple VirtualHosts in Apache

Lately I’ve been configuring all the django apps I manage to work via https exclusively. Some of the servers host multiple apps under different VirtualHost configs and I wanted a simple way to redirect HTTP traffic to HTTPS. The solution I came up with was to create a “global” config that resides in /etc/apache2/conf.d/[name of global config file].conf; it looks something like this:

NameVirtualHost *:80
NameVirtualHost *:443

<VirtualHost *:80>
    ServerName apps.domain.com
    RedirectMatch 301 /(.*)$ https://apps.domain.com/$1
</VirtualHost>

<VirtualHost *:80>
    ServerName someothervhost.domain.com
    RedirectMatch 301 /(.*)$ https://someothervhost.domain.com/$1
</VirtualHost>

Include /srv/apps/appname1/apache/appname1.conf
Include /srv/apps/appname2/apache/appname2.conf

Then, all I need to do is put my application-specific config options in their respective config files:

#appname1.conf
<VirtualHost *:443>
    ServerAdmin me@domain.tld
    ServerName apps.domain.com
    [...]
</VirtualHost>
#appname2.conf
<VirtualHost *:443>
    ServerAdmin me@domain.tld
    ServerName someothervhost.domain.com
    [...]
</VirtualHost>

… and so on, and so forth. This technique scales well — you can add as many vhosts as you need and you can configure their redirects/include their config files from within the global config. If you wanted to, you could even put the redirect directives within each individual app’s apache config — it makes no difference as long as you put the Include directives in your global config. Probably the best part of this method is that you do not have to mess with mod_rewrite. See this link for more information.

Additionally, if you see the following error upon restarting apache:

[Tue Dec 31 23:59:59 2013] [warn] NameVirtualHost *:80 has no VirtualHosts

Edit /etc/apache2/ports.conf and comment out (or remove it entirely) the line that reads:

NameVirtualHost *:80

Here’s an example of a “bare bones” ports.conf that will get rid of the warning message while allowing you to implement the redirect method above:

Listen 80
<IfModule mod_ssl.c>
    Listen 443
</IfModule>

<IfModule mod_gnutls.c>
    Listen 443
</IfModule>