Redirect Magento URLs to HTTPS and www using htaccess

Google promotes websites that have an SSL certificate installed by placing them higher in the search results. This requires configuration changes within Magento.

Configuration within the Magento admin

Assuming you have a valid SSL, you can enable secure links in the frontend and admin by changing the Use Secure URLs on Storefront and Use Secure URLs in Admin options respectively.

By default, this will enable HTTPS urls when in the admin panel, and in terms of the frontend, when navigating to the customer login and register pages, as well as the checkout.

Whilst using secure URLs provides customers with confidence that they’re shopping on a secure website, a small problem poses itself in terms of the accessibility of your website on HTTP and HTTPS URLs.

If you navigate to a page that Magento uses secure URLs on, such as the customer login page, and then navigate back to the home page, the home page will use HTTPS. That’s good, but you’ll also notice that you can navigate to the home page by also using plain HTTP.

Configuration within htaccess

Whilst search engines such as Google might be intelligent enough to not count pages accessible using HTTP and HTTPS as duplicate content, it is always worth correcting this by adding redirect configuration in the .htaccess file.

This involves redirecting all URLs access via HTTP to HTTPS. The code to do this is fairly simple, simply drop the following snippet within the <IfModule mod_rewrite.c> section after the RewriteEngine on line.

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

This works nicely. Now consider if your website uses the www subdomain and whether this should show as part of the website URL. If your website doesn’t use www, then the redirect configuration above will work just fine. If www is in use, then you could replace the above snippet of code with the below.

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

This will correctly redirect non-www HTTP URLs to the HTTPS www version, however it will not redirect HTTP URLs with www to HTTPS.

To ensure that all types of HTTP URLs are correctly redirected to www HTTPS, add the following into your .htaccess.

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

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

This will also cover the scenario of when you have a single site security certificate which only covers one domain – that is either the non-www or www version and not both. Trying to access a page without HTTPS and www. (or whichever domain your certificate covers) will display an red warning screen before it even gets to receive the redirect to the safe and correct HTTPS URL.