如何在Azure与Nginx环境下获取正确的重写URL?
问题描述
我有一个运行在Docker容器中的应用,监听5080端口的HTTP流量。服务器以Nginx作为反向代理,监听443端口HTTPS流量,将匹配example.com的请求代理至http://127.0.0.1:5080/,这部分运行正常。
应用采用Azure OpenID认证,Azure端已配置回复URL为https://example.com/_renarde/security/oidc-success,但登录完成后跳转回应用时出现错误:
The redirect URI 'http://127.0.0.1:5080/j_oauth_callback' specified in the request does not match the redirect URIs configured for the application
尝试过proxy_redirect配置但未解决问题,需要让后端应用向Azure发送回调URL时使用原始域名https://example.com而非代理地址。
当前Nginx配置:
server { server_name example.com; # managed by Certbot location / { proxy_pass http://127.0.0.1:5080/; proxy_redirect http://127.0.0.1:5080/ https://example.com/; proxy_set_header Host $proxy_host; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } listen 443 ssl; # managed by Certbot ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem; # managed by Certbot include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot }
解决方案
问题根源是后端应用生成回调URL时,使用了Nginx代理传递的Host头(当前为127.0.0.1:5080)和自身监听的HTTP协议,导致回调地址变成了内部代理地址而非外部真实域名。需要通过Nginx传递正确的请求头,让后端应用感知外部的真实域名和协议:
- 修正
Host头:将proxy_set_header Host $proxy_host;改为proxy_set_header Host $host;,使后端收到的Host为外部访问的域名example.com,而非代理目标地址。 - 添加
X-Forwarded-Proto头:告诉后端应用外部请求使用HTTPS协议,避免生成HTTP的回调地址。 - (可选)添加
X-Forwarded-Host头:进一步明确外部请求的主机名,部分框架会优先读取这个头。
修改后的Nginx配置:
server { server_name example.com; # managed by Certbot location / { proxy_pass http://127.0.0.1:5080/; proxy_redirect http://127.0.0.1:5080/ https://example.com/; proxy_set_header Host $host; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; proxy_set_header X-Forwarded-Host $host; } listen 443 ssl; # managed by Certbot ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem; # managed by Certbot include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot }
额外注意:
- 确保应用框架/OpenID客户端配置中启用了对X-Forwarded系列头的支持,比如部分Java框架需要设置信任反向代理的参数,Python Flask需配置
PREFERRED_URL_SCHEME等。只有应用读取这些头,才能正确生成外部回调URL。 - 确认Azure端的回复URL与应用生成的回调地址完全一致(包括路径),当前错误中的路径是
/j_oauth_callback,但配置的是/_renarde/security/oidc-success,需检查应用的OIDC配置是否正确指定了回调路径,确保两边匹配。
内容的提问来源于stack exchange,提问作者Dave Cassel
相关产品推荐
相关产品推荐

