2
\$\begingroup\$

I would like to know if this code in .htaccess for forcing SSL and WWW in URL is correct, because with another code I usually get redirect loop, e.g. RewriteCond %{HTTPS} !=on and now it works like a charm (suspiciously). Also, is it possible to write it better/simpler?

# Force to SSL
RewriteCond %{HTTP:HTTPS} !1
RewriteRule ^(.*)$ https://%{HTTP_HOST}/$1 [R=301,L]

# Force to WWW
RewriteCond %{HTTP_HOST} !^www\.(.*)$ [NC]
RewriteRule ^(.*)$ https://www.%{HTTP_HOST}/$1 [R=301,L]  
\$\endgroup\$
  • 1
    \$\begingroup\$ I'm not convinced that this works. Do you have some special setup such that HTTPS requests all have a non-standard HTTPS: 1 header? \$\endgroup\$ – 200_success Jul 12 '14 at 18:56
  • \$\begingroup\$ Only this code do that job correctly, but I don't know what this mean - RewriteCond %{HTTP:HTTPS} !1 \$\endgroup\$ – user2406937 Jul 12 '14 at 23:55
2
\$\begingroup\$

What you're doing with RewriteCond %{HTTP:HTTPS} !1 is checking whether the HTTPS header is present in the request and if it is, then the value is not 1.

%{HTTP:header}, where header can be any HTTP MIME-header name, can always be used to obtain the value of a header sent in the HTTP request. Example: %{HTTP:Proxy-Connection} is the value of the HTTP header Proxy-Connection:.

Though, I think it'd be easier to use %{HTTPS} instead.

%{HTTPS}

Will contain the text "on" if the connection is using SSL/TLS, or "off" otherwise. (This variable can be safely used regardless of whether or not mod_ssl is loaded).

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

Also, you are not using QSA flag. This might cause in undesired behaviour.

| improve this answer | |
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.