I have seen couple of solutions to 301 redirect non www http i.e. http://domain-name to https://www.domain-name but all of them (in my experience) gives 2 redirects.
Either they first redirect from non www to www first and than http to https or in 2nd redirect first and than 1st redirect. One of the example of such code is:
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule .* https://www.example.com%{REQUEST_URI} [L,R=301]
RewriteCond %{HTTPS} off
RewriteRule .* https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
The best solution would be one 301 redirect which takes care of both i.e. non www as well as http part. Can anyone please suggest me the right code.
Best rgds,
Jai
CodePudding user response:
I am using this code and I get only one 301 redirect (to https://www.example.com) when I test http://example.com with httpstatus.io
# ensure www
RewriteCond %{HTTP_HOST} !^www.example.com$ [NC]
RewriteRule ^(.*)$ https://www.example.com/$1 [L,R=301]
# ensure https
RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteCond %{HTTPS} off
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
The first rule, if your address doesn't start with www will be redirected to the https www (one redirect)
The second rule applies only if your address starts with a www (because of rule 1) and it doesn't contain https. (one redirect)
Indeed, your domain http://infocera.com is getting 2 redirects.
Using @MrWhite's suggestion about your domain going through Cloudflare: you should go to your domain in Cloudflare -> Rules -> Page Rules and delete any rule you have about redirecting.
CodePudding user response:
I suggest to combine both rules into a single one by combining both conditions:
RewriteEngine on
RewriteCond %{HTTP_HOST} !^www\. [NC] [OR]
RewriteCond %{HTTPS} off
RewriteRule ^ https://www.example.com%{REQUEST_URI} [L,R=301]
That is simple, thus easy to understand for anyone maintaining the site.
The only drawback would be that you have to specify a fixed http host in the target rule. Which is perfectly fine except if you host multiple domains and hope to find a solution working for all of them at once.
I would generally advise against such an attempt though. Such general rules have nothing to do with an application logic, one should always prefer to implement such general rule in the actual http server's host configuration instead of using distributed configuration files (".htaccess"). That means that you have separate configurations for separate domains, which again allows to place such rule into the separate configuration files while still having only a single actual redirection that is performed.