Correctly redirect your non-https and non-www traffic

Correctly redirecting non-www and https (SSL) traffic is crucial for Search Engine Optimization (SEO). With just a few lines in your .htaccess file (Apache only) you can redirect all incoming links independent of the domain.

RewriteEngine On

RewriteCond %{HTTPS} off [NC]
RewriteCond %{HTTP_HOST} !^www\\.(.*)$ [NC]
RewriteRule (.*) https://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

RewriteCond %{HTTP_HOST} !^www\\.(.*)$ [NC]
RewriteRule (.*) https://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

What is this doing?

RewriteEngine On

Enable the Apache rewrite engine.

RewriteCond %{HTTPS} off [NC]

Execute the rewrite rule only if the current request is not on SSL. [NC] makes the definition case-insensitive.

RewriteCond %{HTTP_HOST} !^www\\.(.*)$ [NC]

Also redirect if the current hostname lacks www..

RewriteRule (.*) https://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

Execute the actual redirect with status code 301. Redirect to the current hostname including www. and any request paths and parameters that were used.

RewriteCond %{HTTP_HOST} !^www\\.(.*)$ [NC]

This is a second check if the current request lacks www.. It will check all requests over SSL as the previous rewrite already made sure our connections are over SSL.

RewriteRule (.*) https://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

Again redirect any non-www requests to a request including www..

Test

Always test these kind of snippets on a test or staging environment. Different setups can behave differently so make sure it behaves like you expect and actually need it.