Apache: Redirecting HTTP to HTTPS and WWW to Non-WWW

I was reading through the Apache documentation the other day as part of work on one of my pet projects (Thumber.co) and came across the following little tidbit (emphasis added).

mod_rewrite should be considered a last resort, when other alternatives are found wanting. Using it when there are simpler alternatives leads to configurations which are confusing, fragile, and hard to maintain.

Apache docs

Well, this got me thinking. I was in the process of updating Thumber to have everything redirect to HTTPS with no WWW prefix. I had implemented this functionality with mod_rewrite, but after reading the above I felt like making this better so I set out to convert redirects to use the basic Redirect directive, as provided by mod_alias.

My mod_rewrite starting point before any changes looked something like the following:

<VirtualHost *:80>
 ServerName thumber.co
 ServerAlias www.thumber.co

 RewriteEngine On
 RewriteRule ^ https://thumber.co%{REQUEST_URI} [L,QSA,R=301]
</VirtualHost>

<VirtualHost *:443>
 ServerName thumber.co
 ServerAlias www.thumber.co

 RewriteEngine On
 RewriteCond %{HTTP_HOST} ^www\.
 RewriteRule ^ https://thumber.co%{REQUEST_URI} [L,QSA,R=301]
</VirtualHost>

With the above, if the HTTP virtual host was hit, it would redirect to the non-WWW HTTPS equivalent  path. If the HTTPS virtual host was hit and www.thumber.co was the host then it would redirect to thumber.co. This seemed pretty clean as far as mod_rewrite go, but its still mod_rewrite. The following is what I came up with as a replacement.

<VirtualHost *:80>
 ServerName thumber.co
 ServerAlias www.thumber.co

 Redirect permanent / https://thumber.co/
</VirtualHost>

<VirtualHost *:443>
 ServerName thumber.co
 ServerAlias www.thumber.co

 <If "%{HTTP_HOST} == 'www.thumber.co'">
  Redirect permanent / https://thumber.co/
 </If>
</VirtualHost>

Much more straightforward! The only gotcha in the above is that the If directive is new to Apache 2.4. If you’re running an older version, you may still be stuck with mod_rewrite for the HTTPS virtual host, though the HTTP virtual host could still use the Redirect directive in an older Apache version.

Leave a Reply