Apache — Redirect all HTTP requests to HTTPS

This post describes the process of forcing all HTTP traffic to HTTPs.

If we all lived in a perfect world, there would be no need for security. However, we don't, so there is.

One way you can help increase the security of your site and therefore your data, is to only implement ssl protocol in the server, or to block non ssl traffic via the firewall.

Although these methods are valid, there are sometimes real world issues that get in the way. Perhaps you don't have admin access to the server software, or maybe there is no firewall internally in your organization. No matter the reason, there are times when you want to redirect all non-secure traffic to a secure channel...namely redirect http to https.

This can be done in the apache config file for the virtual host, or can be added to the .htaccess in the sites root.

  • Here are the steps to do the rewrite in the .htaccess file.
  • Change to the web root folder for the site.
  • Edit the .htaccess file
  • Add the lines
    • RewriteEngine on
    • RewriteCond %{SERVER_PORT} !^443$
    • RewriteRule ^.*$ https://%{SERVER_NAME}%{REQUEST_URI} [L,R]

If preferable you can wrap the rewrite commands in an IfModule test like;

<IfModule mod_rewrite.c>
RewriteEngine on
RewriteCond %{SERVER_PORT} !^443$
RewriteRule ^.*$ https://%{SERVER_NAME}%{REQUEST_URI} [L,R]
</IfModule>
  • RewriteCond, if the condition is met, in this case that the connection is NOT port 443, execute the RewriteRule.
  • RewriteRule, takes three parameters of Pattern, Substitution and the optional flags. In our case, the patter to match is the entire string, ^.*$, the replacement is to overwrite the entire request with the https protocol and the same server name and requested resource, https://%{SERVER_NAME}%{REQUEST_URI}. Finally, the flags, in our case we specify 2 flags, the L flag says to stop processing rules and the R flag causes the server to redirect the client to the re-written uri.

I hope you found this helpful.

Leave a Reply