Nginx 使用 proxy_pass 后在 Java 中 getRequestUrl() 的问题

在做一个 CAS 系统,业务系统发现用户没有登录后引导跳转到 CAS。

业务系统1域名:benchmark-1.xxx.com
业务系统2域名:benchmark-2.xxx.com
CAS域名:cas.xxx.com

nginx 配置如下:

server {
    listen 80;
    server_name cas.xxx.com;

    location / {
        proxy_pass http://localhost:8090;
    }
}

server {
    listen 80;
    server_name benchmark-1.xxx.com;

    location / {
        proxy_pass http://localhost:8095;
    }
}

server {
    listen 80;
    server_name benchmark-2.xxx.com;

    location / {
        proxy_pass http://localhost:8096;
    }
}

现在我访问业务系统1,http://benchmark-1.xxx.com/us...,发现没有登录,拦截器 redirect 请求到 http://cas.xxx.com/auth/login。在拦截器里面我获取了当前请求的 URL:

String requestUrl = request.getRequestURL().toString();

当页面跳转后观察到浏览器地址栏的主机变成了 localhost:8095

http://cas.xxx.com/auth/login?redirectUrl=http://localhost:8095/user/get

这样我的 CAS 就没有办法重定向回业务系统。我现在定位是 Nginx 配置 proxy_pass 的问题,但是不知道怎么改,请各位不吝赐教。

阅读 4.9k
2 个回答

自问自答!!!

只需要在 proxy_pass 之前把原始的主机名相关的东西往代理里面设置一下就可以了。

location / {
    proxy_set_header Host $host;
    proxy_set_header X-Real-Ip $remote_addr;
    proxy_set_header X-Forwarded-For $remote_addr;
    proxy_pass http://localhost:8095;
}

这个不是nginx的问题,而是后台系统的配置问题。因为你经过了反向代理,在后台系统看来你访问的就是http://localhost:8095/user/get,因此就给你redirect过去了。

这种情况必须在后台有相应的配置,能配置用户访问的真正的URL。比如Jenkins,GitLab等等软件,经过反向代理访问必须在后台(GitLab是配置文件)配置一个用户访问的URL。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题