0

I start reading about a similar topic at this page .htaccess - how to force "www." in a generic way? and the solution was not, well almost what I am looking to do.

The problem : I need the user to be on HTTPS and on WWW to make my application working properly. But if some one click on a html link like:

<a href="https://www.example.com">www.example.com</a>

The user will fall on my website with this :

https://www.www.example.com/

Here is my current .htaccess file.

<IfModule mod_rewrite.c>

RewriteEngine on

RewriteCond %{HTTP_HOST} !^www\.

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

RewriteCond %{HTTPS} !=on

RewriteRule ^/?(.*) https://www.%{SERVER_NAME}/$1 [R=301,L]

</IfModule>

Is there any way to detect that the user already entered the WWW or is there a best practice to get the result I am looking for?

Thank you.

Community
  • 1
  • 1
Patrice Poliquin
  • 364
  • 9
  • 21
  • If you want to force HTTPS, you should use HSTS too. It's really more secure (it protect against sslstrip for example). Read careful the docs. – Tom Aug 16 '16 at 19:50

1 Answers1

3

You are getting this behavior because http -> https rule is adding www\. in target URL without checking if URL is already starting with www.

You should replace both of your rules with this single rule and as a bonus avoid multiple redirects:

RewriteEngine On

RewriteCond %{HTTP_HOST} !^www\. [NC,OR]
RewriteCond %{HTTPS} off
RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$ [NC]
RewriteRule ^ https://www.%1%{REQUEST_URI} [R=301,L,NE]
anubhava
  • 664,788
  • 59
  • 469
  • 547