Apache HTTP to HTTPS redirects don't need to be painful!

By Gavin Phillips @ Cowshed Works Ltd

Blog Picture

For anyone looking at the daunting task of moving large websites from HTTP to HTTPS and trying to maintain search engine rankings there's a lot of information out there on how best to do it.

The majority of tutorials and articles I've read on the topic suggest using some regex in apache's RewriteRule to achieve the result. The usual code snippet (provided by an old apache page) is quite often this:

RewriteEngine On
# This will enable the Rewrite capabilities

RewriteCond %{HTTPS} !=on
# This checks to make sure the connection is not already HTTPS

RewriteRule ^/?(.*) https://%{SERVER_NAME}/$1 [R,L]
# This rule will redirect users from their original location, to the same location but using HTTPS.
# i.e.  http://www.example.com/foo/ to https://www.example.com/foo/
# The leading slash is made optional so that this will work either in httpd.conf
# or .htaccess context

Whilst this will work there's a gotcha here and also a much easier way to do it without the risk. Firstly, the gotcha is that if you don't configure the rewrite correctly you could end up with the default response code of 302 going back to the browser, the above code sends a 302, don't take my word for it...

Any valid HTTP response status code may be specified, using the syntax [R=305], with a 302 status code being used by default if none is specified.

Source https://httpd.apache.org/docs/current/rewrite/flags.html

The issue here is that what you're trying to achieve is permanently shifting the url to a new location, this should force all indexing systems (such as search engines) to update their records with the new url. The response code to achieve this result is a 301 redirect, not a 302 redirect.

302 Found

The requested resource resides temporarily under a different URI

301 Moved Permanently

The requested resource has been assigned a new permanent URI and any future references to this resource SHOULD use one of the returned URIs.

So, what's the easy way to handle these HTTP to HTTPS redirects?

Are you sitting down? Because there's some serious config code about to drop, are you ready? Here it is.......


Redirect permanent "/" "https://www.example.com/"

Now, isn't that easier? A one-liner, difficult to mess up (not impossible) and it returns a 301 as we've told it the redirect is permanent, a beautifully fluent line of config.

I've used this on lots of redirects and it's working perfectly, no issues of tanked search results or infinite redirect loops.

Problem solved, you're welcome :)

Author: Gavin Phillips
Published: Feb 1, 2017 (1 year ago)

Work with Cowshed:Works

Ready to start your next website or app project? Give us a call or send us an email.



© Cowshed Works Ltd: UK Staffordshire-based website design, build and management

VAT: 251 4480 22 - Registered in England: 10399485

Terms: Website | Service