【问题标题】:Running spring boot application behind nginx - missing location prefix when redirect在 nginx 后面运行 spring boot 应用程序 - 重定向时缺少位置前缀
【发布时间】:2020-02-08 05:34:03
【问题描述】:

我在 URL:http://localhost:8080 上运行 Spring Boot 应用程序,有两个端点:

/endpoint1
/login2 - login page for authentication

然后我在代理服务器后面运行它 - nginx 在端口 81 上运行。在 nginx 配置中我放了这样的东西:

location / {
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header X-Forwarded-Proto $scheme;
            proxy_set_header X-Forwarded-Port $server_port;
            proxy_set_header Host $host;
            proxy_pass http://localhost:8080/;

        }

然后一切正常:当我使用http://localhost:81/endpoint1 时,我被重定向到http://localhost:81/login2

但是我希望我的 nginx 应用程序 URL 看起来像 http://localhost:81/my_prefix/login2。所以我在 nginx 配置中添加了前缀:

location /my_prefix/ {
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header X-Forwarded-Proto $scheme;
            proxy_set_header X-Forwarded-Port $server_port;
            proxy_set_header Host $host;
            proxy_pass http://localhost:8080/;

        }

但是当我尝试使用 URL:http://localhost:81/my_prefix/endpoint1 时,我被重定向到:http://localhost:81/login2 - 没有 /my_prefix

在我的 Spring WebSecurityConfigurerAdapter 配置类中,我有一些安全配置,带有用于身份验证的登录页面:

@Override
protected void configure(final HttpSecurity http) throws Exception {
            http.csrf().disable()
                    .addFilterBefore(authenticationFilter(), UsernamePasswordAuthenticationFilter.class)
                    .authorizeRequests()
                    .antMatchers("/", "/metadata", "/favicon.ico", "/api/**", "/*.css", "/*.js").permitAll()
                    .antMatchers("/admin/**").hasRole("ADMIN")
                        .anyRequest().hasRole("USER").and()
                            .formLogin().loginPage("/login2").permitAll()
                    .and()
                        .logout().logoutSuccessUrl("/");
        }

我还有财产:server.use-forward-headers: true

如何在重定向到登录页面时强制 Spring MVC 包含 nginx 位置前缀 (/my_prefix)?

【问题讨论】:

    标签: spring spring-boot spring-mvc nginx redirect


    【解决方案1】:

    你需要改变这个:

    proxy_pass http://localhost:8080/;
    

    到这里:

    proxy_pass http://localhost:8080;
    

    【讨论】:

      【解决方案2】:

      您需要从您的 nginx 发送一个标头 X-Forwarded-Prefix: /my_prefix 并在 Spring Boot application.yaml 中启用转发标头

      server.forward-headers-strategy: FRAMEWORK
      

      Running Behind a Front-end Proxy Server

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-08-27
        • 1970-01-01
        • 2018-10-01
        • 1970-01-01
        • 2020-05-26
        • 2018-03-10
        • 1970-01-01
        • 2021-06-27
        相关资源
        最近更新 更多