Why is Apache explicitly forcing redirect with an absolute url?
Solution 1:
All external redirects (R
flag) result in mod_rewrite requiring an absolute URL. When you don't explicitly include the scheme and hostname in the RewriteRule
substitution then Apache will use the current protocol, server name and port. Apache (or strictly speaking, mod_rewrite) doesn't send a relative URL back in the Location:
HTTP response header hoping that the user-agent will resolve the URL.
(It was not until June 2014 (RFC 7231) that relative URLs in the Location:
header officially became part of the standard. So, particularly if you're still on Apache 2.2, then it's difficult to argue that Apache is doing anything wrong here.)
If Apache is sending back an HTTP URL (as opposed to HTTPS) then it would seem that Apache is serving the response back over HTTP, not HTTPS.
Yes, you could manually "fix" the URL using mod_rewrite. However, the REQUEST_SCHEME
server variable is likely to have the same "problem". If you are behind a proxy then you might need to check the X-Forwarded-Proto
header (or similar) as to whether it's "http" or "https".
As well as (conditionally) forcing HTTPS in the directive itself, you can also force HTTPS in the server config with the ServerName
(and UseCanonicalName
) directive(s). However, I assume that is not desirable and you need to be flexible?
You can also edit the Location:
header, before it is sent back to the client. Using mod_headers you can force a relative URL by manually stripping out the scheme + hostname, as suggested in this StackOverflow answer:
Header edit Location "^https?://[a-zA-Z0-9.-]+" ""
Further reference:
- https://stackoverflow.com/questions/16297233/how-to-rewrite-location-response-header-in-a-proxy-setup-with-apache
- https://stackoverflow.com/questions/8250259/is-a-302-redirect-to-relative-url-valid-or-invalid