从 spring 重定向 url 中删除项目名称前缀

remove project name prefix from spring redirect url

我使用 nginx 反向代理连接 tomcat 并且 nginx 配置是:

server {
  listen      80;
  listen [::]:80;
  server_name magnet.s-m.local;

  location / {
      proxy_pass http://tomcat:8080/magnet/;
      proxy_cookie_path /magnet /;
      proxy_redirect     off;
      proxy_set_header   Host $host;
      proxy_set_header   X-Real-IP $remote_addr;
      proxy_set_header   X-Forwarded-For $proxy_add_x_forwarded_for;
      proxy_set_header X-Forwarded-Host $server_name;
  }
}

一切都可以,但是当我想重定向用户时 spring 添加项目名称到重定向路径。

@RequestMapping(value = "/login",method = RequestMethod.POST)
public String loginCheck(HttpSession session, @RequestParam("username") String user, @RequestParam("password") String password){
    session.setAttribute("username",user);
    return "redirect:/home";
}

此代码重定向到 http://magnet.s-m.local/magnet/home 但我想重定向 http://magnet.s-m.local/home

如果我使用 RedirectView 效果很好,但使用 redirect:/home 更好,因为如果登录失败,我可以决定重定向或加载 jsp 文件。

尝试从您的 nginx 配置中删除 proxy_redirectproxy_set_header Host 参数:

location / {
    proxy_pass http://tomcat:8080/magnet/;
    proxy_cookie_path /magnet /;
    proxy_set_header   X-Real-IP $remote_addr;
    proxy_set_header   X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header X-Forwarded-Host $server_name;
}

您也可以更详细地指定proxy_redirect,但它应该被激活。