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]
1 Answer 1
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 anyHTTP 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 headerProxy-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.
HTTPS: 1
header? \$\endgroup\$RewriteCond %{HTTP:HTTPS} !1
\$\endgroup\$