我不是 nginx 管理方面的专家,我只是一名开发人员。我有两个后端在 docker 中运行。让我给它们命名
- 后端1:8080
- 后端2:8081
另外,我安装了 letsencrypt 证书,并公开了 443 端口的 Nginx。我的 Nginx 配置是(环境变量 FQDN 类似于 example.com)
upstream backend1 {
server backend1:8080;
}
upstream backend2 {
server backend2:8081;
}
server {
listen 443 ssl;
server_name ${FQDN} www.${FQDN};
ssl_certificate /etc/letsencrypt/live/${FQDN}/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/${FQDN}/privkey.pem;
ssl_session_cache shared:SSL:1m;
ssl_session_timeout 5m;
ssl_ciphers HIGH:!aNULL:!MD5;
ssl_prefer_server_ciphers on;
if ($server_port = 80) { set $https_redirect 1; }
if ($host ~ '^www\.') { set $https_redirect 1; }
if ($https_redirect = 1) { return 301 https://${FQDN}$request_uri; }
location /path1/ {
proxy_pass http://backend1/;
proxy_redirect ~^/(.*) $scheme://$http_host/path1/$1;
proxy_http_version 1.1;
proxy_pass_header Set-Cookie;
proxy_pass_header Cookie;
proxy_pass_header X-Forwarded-For;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header Host $http_host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forward-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forward-Proto http;
proxy_set_header X-Nginx-Proxy true;
add_header X-Upstream $upstream_addr;
}
location /path2/ {
proxy_pass http://backend2/;
proxy_redirect ~^/(.*) $scheme://$http_host/path2/$1;
proxy_http_version 1.1;
proxy_pass_header Set-Cookie;
proxy_pass_header Cookie;
proxy_pass_header X-Forwarded-For;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header Host $http_host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forward-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forward-Proto http;
proxy_set_header X-Nginx-Proxy true;
add_header X-Upstream $upstream_addr;
}
}
我希望如果我发出请求https://exapmle.com/path1/
,Nginx 应该转到http://backend1:8080/
该服务器并返回响应。问题是 backend1(以及 backend2)可以响应 302 并重定向到某个路径,例如。Nginx/login
将我的浏览器重定向到,https://exapmle.com/login
但我希望它将我重定向到https://exapmle.com/path1/login
您能否帮助我并指出我在配置中犯的错误。我已经查看了 SO 中所有类似的问题,但没有找到任何解决方案。我还浏览了 Nginx 文档,但也没有找到答案。
我有这条线路proxy_redirect ~^/(.*) $scheme://$http_host/path1/$1;
,我想它一定能完成我想要的工作。
顺便说一句,我无法在 Nginx 配置中占用 / 位置(为根路径创建配置),因为它已保留给另一个后端服务器。提前致谢。
答案1
可能是因为您的配置中的 X-Forwarded-Headers 拼写错误。它应该是X-Forwarded-*
而不是X-Forward-*
。
答案2
location /path1/ {
proxy_pass http://backend1/;
proxy_redirect default;
proxy_redirect / /path1/;
proxy_redirect http://backend1/ https://exapmle.com/path1/;
proxy_http_version 1.1;
proxy_pass_header Set-Cookie;
proxy_pass_header Cookie;
proxy_pass_header X-Forwarded-For;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header Host $http_host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forward-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forward-Proto http;
proxy_set_header X-Nginx-Proxy true;
add_header X-Upstream $upstream_addr;}
那没问题;