Created
May 17, 2024 17:50
-
-
Save un-def/e0f88bc3b50fa1825a949ec74b5ad52d to your computer and use it in GitHub Desktop.
Nginx fix Location header on redirects behind reverse proxy
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
http { | |
map $http_x_forwarded_proto=$http_x_forwarded_port $redirect_port { | |
http=80 ''; | |
https=443 ''; | |
default :$http_x_forwarded_port; | |
} | |
server { | |
listen 8080; | |
location / { | |
proxy_pass http://unix:/tmp/nginx.sock; | |
proxy_set_header Host $host; | |
proxy_buffering off; | |
proxy_request_buffering off; | |
proxy_redirect http://$host/ $http_x_forwarded_proto://$http_x_forwarded_host$redirect_port/; | |
} | |
} | |
server { | |
listen unix:/tmp/nginx.sock; | |
location / { | |
root /data; | |
autoindex on; | |
} | |
} | |
} |
Nginx Lua Module:
header_filter_by_lua_block {
local location = ngx.header.location
if location and string.sub(location, 1, 1) == '/' then
local proto = ngx.var.http_x_forwarded_proto
local host = ngx.var.http_x_forwarded_host
local port = ngx.var.http_x_forwarded_port
if proto == 'http' and port == '80' or proto == 'https' and port == '443' then
location = string.format('%s://%s%s', proto, host, location)
else
location = string.format('%s://%s:%s%s', proto, host, port, location)
end
ngx.header.location = location
end
}
Apparently this is no longer necessary.
RFC 2616 Hypertext Transfer Protocol -- HTTP/1.1, June 1999 requires an absolute URI: 14.30 Location.
RFC 7231 Hypertext Transfer Protocol (HTTP/1.1): Semantics and Content, June 2014, which obsoletes RFC 2616, allows a relative URI: 7.1.2. Location.
RFC 9110 HTTP Semantics, June 2022, which obsoletes RFC 7231, allows a relative URI: 10.2.2. Location.
TL;DR use absolute_redirect off
.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The problem: