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] 
Jamal
35.2k13 gold badges134 silver badges238 bronze badges
asked Jul 12, 2014 at 9:04
\$\endgroup\$
2
  • 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\$ Commented Jul 12, 2014 at 18:56
  • \$\begingroup\$ Only this code do that job correctly, but I don't know what this mean - RewriteCond %{HTTP:HTTPS} !1 \$\endgroup\$ Commented Jul 12, 2014 at 23:55

1 Answer 1

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.

answered Nov 5, 2014 at 18:54
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.