How to Redirect Non-SSL to Secure/SSL Links in Apache

When you migrate your site to secure/SSL links there might be still links to older pages/posts that are using non-secure links. You can use the following snippet that can be added to the .htaccess or in the virtual host file. Those rules will do the SSL redirect for you. Using .htaccess is faster than relying on a WordPress plugin to do the SSL redirect for you.

Keep in mind that these rules apply to Apache web server only.

It will redirect users that have accessed http://example.com -> https://example.com

# https://wpmove.net - redirect to https
<IfModule mod_rewrite.c>
	RewriteCond %{HTTPS} off
	RewriteCond %{REQUEST_URI} !^/.well-known
	RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,QSA,R=301]
</IfModule>

There are several checks before the redirect is done.

There’s an HTTPS environment variable that Apache sets when the site is accessed via secure channel.

There is a check for .well-known which is used by certbox/let’s encrypt to verify the domain name.

We have it that like that because certbot/let’s encrypt creates a temporary file and accesses it from that specific folder.

The RewriteRule is where the real magic happens if all the conditions have been met.

We redirect to the https version of the site and append the request
e.g. http://example.com/services/wp-migration => https://example.com/services/wp-migration

QSA flags means that Apache will also append any parameters that have been passed to the URL as well.

R=301 is the redirect status code which is 301 which means permanent redirect.

That will instruct the search engines that we care about the new link structure more.

Leave a Comment

Your email address will not be published. Required fields are marked *