1

I have a requirement to check for non HTTPS URLs in htaccess.

My understanding is that RewriteCond %{HTTPS} !=on will match all URLs that are not HTTPS. But upon testing, I find RewriteCond %{HTTPS} !=on is matching both HTTP and HTTPS URLs.

However, RewriteCond %{SERVER_PORT} !^443$ is matching non HTTPS URLs correctly? Am I missing something regarding the understanding of %{HTTPS} !=on?

  • Would RewriteCond %{SERVER_PORT} ^443$ match HTTPS URLs? – MrWhite Sep 24 '18 at 0:08
1

My understanding is that RewriteCond %{HTTPS} !=on will match all URLs that are not HTTPS.

Yes, that is correct. In this context, HTTPS is a server variable, set by Apache based on the request hitting your server.

But upon testing, I find RewriteCond %{HTTPS} !=on is matching both HTTP and HTTPS URLs.

That's not possible if the SSL cert is installed directly on your application server. However, if you are using an SSL proxy, whereby the SSL is handled by a front-end proxy and the connection from the SSL proxy to your application server is plain-old HTTP (such is the case with Cloudflare's free Flexible SSL option) then this will indeed appear to be the case because your server is only serving traffic over HTTP.

However, RewriteCond %{SERVER_PORT} !^443$ is matching non HTTPS URLs correctly?

However, this contradicts the above! If this works then so should the check against HTTPS. This would seem to suggest you are perhaps seeing a cached response above?

  • If it is caused by a load balancer, they need a rule based on %{HTTP:X-Forwarded-Proto}. This question on StackOverflow has a rule that redirects unless it either has that header, or Apache is handling the HTTPS itself: stackoverflow.com/questions/26620670/… – Stephen Ostermiller Aug 8 '18 at 15:08
  • "unless it either has that header, or Apache is handling the HTTPS" - Although, for security reasons, you should only be checking the X-Forwarded-Proto HTTP request header if you know you are behind a proxy (or load balancer) that sets it. Otherwise, a potentially malicious request could inject that header and force your system to not behave as it should, eg. not redirect to HTTPS (which is the case with that "generic" solution posted on StackOverflow). – MrWhite Aug 8 '18 at 18:13

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

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