Apache rules to redirect all URLs to HTTPS

Published on 2020-07-04 • Modified on 2020-07-04

In this snippet, we will see how to redirect all URLs of a domain to HTTPS through an Apache vhost. Be careful that I use this when creating a new domain that uses HTTPs. If you have an existing domain and wanting to migrate to HTTPS, you should use rules which preserve the paths. In my case, I wanted to have something straightforward where all URLs requests for http://www.strangebuzz.com and http://strangebuzz.com are redirected to https://www.strangebuzz.com. Note that the redirection from https://strangebuzz.com to http://www.strangebuzz.com is made in the primary vhost. You can test by copy/paste those URLs in your browser and check that the redirections work as expected.

# Handles http://www.strangebuzz.com and http://strangebuzz.com
<VirtualHost *:80>
    ServerName www.strangebuzz.com
    ServerAlias strangebuzz.com

    # Rewrite everything from HTTP to HTTPS
    RewriteEngine on
    RewriteCond %{SERVER_NAME} =www.strangebuzz.com [OR]
    RewriteCond %{SERVER_NAME} =strangebuzz.com
    RewriteRule ^ https://www.strangebuzz.com [END,NE,R=permanent]
RewriteCond %{SERVER_NAME} =strangebuzz.com [OR]
RewriteCond %{SERVER_NAME} =www.strangebuzz.com
RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [END,NE,R=permanent]

 More on Stackoverflow   Read the doc  More on the web  Random snippet

  Work with me!