Apache returning wrong Location header

apache-2.4http-headersredirect

The issue happens when you:

  1. issue a request with the header "Host" including the port, e.g. "Host: www.example.com:80", which is legal as per https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.23. You can do it for instance with curl curl -v -H "Host: www.example.com:80" -X GET -i http://www.example.com
  2. the server issues a redirect to https for that request, in my case using the following RewriteRule
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

I noticed that the "Location" header of the response also includes the port, and it's the same of that specified in the "Host" header of the request. So the server would respond with "Location: https://www.example.com:80", which is wrong.

This happens to me with "Apache/2.4.7 (Ubuntu)", but I noticed the issue also with Varnish cache server. Why does it behave this way? Is there a way to correct this?

Best Answer

HTTP_HOST refers to the Host: header specified, so your configuration works as expected based on what you're telling it to.

If you want to, you can either strip away the port, or specify another by matching it and using a backreference:

Remove port and default to https:

RewriteCond %{HTTP_HOST} ^([^:]+)(:[0-9]+)?$
RewriteRule ^ https://%1%{REQUEST_URI} [R=301,L]

Change the port to something else (8443 here):

RewriteCond %{HTTP_HOST} ^([^:]+)(:[0-9]+)?$
RewriteRule ^ https://%1:8443%{REQUEST_URI} [R=301,L]