Page 1 of 1

[Tutorial] how to have only https://www. home page - Apache

Posted: Wed Oct 07, 2015 1:52 pm
by VictorDrummond
I wanted to make a contribution to Opencart community...

So hope this is of value to those who seek definitive answer to the question:

How to have all incoming requests to home page as SSL only...

Ensuing discussions never really answered this, a situation that leaves perhaps eight (?) possible URL's for home page, not to mention at least three possibles for ever other page...

Nearly all the advice I came across, including many other and even server admin forums, was that it couldn't be done and, when/if code was suggested, including Cpanel auto-compose-the-code-rules, they just did not work, mostly resulting with re-direct loops... Possibly exacerbated by Apache 2.3.xx onwards handling some rules a little differently to pre-2.3.xx Apache.

In wanting to solve this for my owns stores and after researching and testing every redirect rule-set I could find, the following code in .htaccess finally works... And it not only works for home page, it also works for all other pages too.

At this stage of testing, with all the other set-up done correctly, so far results in NO https errors...

Firstly, some notes:

1 - The result of below implementation is hhtps://www. Although would be adaptable to achieve https:// only.

2 - Assumes http_server is defined as https://www. in config.php and admin/config.php which makes all the internal link correct with NO http errors.

3 - Addon store1 setup URL within "store setting" is defined as https://www.addon1'sdomainname.com

Firstly, test the following ingoing requests for yourself:
(on hover-over these links, note the URL your browser is actually targeting).
http my main store
http/www my main store
http my add-on store1
http/www my add-on store1

The following redirect rules have been applied into .htaccess...
Part of the trick of this rules set is what server port is asked to be listened to...
Apache default port 80 for http, port 443 for https .

RewriteEngine On

# redirect to https for www
RewriteCond %{SERVER_PORT} 80
RewriteCond %{HTTP_HOST} ^www.example.com$ [OR]
RewriteCond %{HTTP_HOST} ^www.addon1toexample.com$
RewriteRule ^(.*)$ https://%{HTTP_HOST}/$1 [R=301,L]

# redirect to https for non-www
RewriteCond %{SERVER_PORT} 80
RewriteCond %{HTTP_HOST} ^example.com$ [OR]
RewriteCond %{HTTP_HOST} ^addon1toexample.com$
RewriteRule ^(.*)$ https://www.%{HTTP_HOST}/$1 [R=301,L]

# to www for https
RewriteCond %{HTTP_HOST} !^www\.
RewriteCond %{SERVER_PORT} 443
RewriteCond %{HTTP_HOST} example.com$ [OR]
RewriteCond %{HTTP_HOST} addon1toexample.com$
RewriteRule ^(.*)$ https://www.%{HTTP_HOST}/$1 [R=301,L]

Hope you find it useful.

Cheers - V