首页 文章

nginx背后的Spring启动应用程序重定向不正确

提问于
浏览
1

我正在尝试使用我在Running a Spring Boot app behind nginx找到的配置文件在nginx后面(在开发机器上)运行我的spring启动应用程序 . 然而,Firefox表示它没有正确重定向,并且javascript控制台中的网络选项卡确认了许多302重定向 .

这是我正在使用的nginx.conf:

http {
include       mime.types;
default_type  application/octet-stream;

log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                  '$status $body_bytes_sent "$http_referer" '
                  '"$http_user_agent" "$http_x_forwarded_for"';

keepalive_timeout  65;

upstream tomcat {
    server localhost:8080;
}

server {
    listen       80;
    server_name  localhost;

    access_log  /var/log/nginx/localhost.access.log  main;

    location / {
            proxy_pass              $scheme://tomcat/$request_uri;
            proxy_redirect          off;
            proxy_set_header        X-Real-IP $remote_addr;
            proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header        Host $http_host;
    }
}

实际上,提到的日志文件有很多这样的行:

127.0.0.1 - - [14/Apr/2018:11:25:38 +0200] "GET /login HTTP/1.1" 302 0 "-" "Mozilla/5.0 (X11; Linux x86_64; rv:59.0) Gecko/20100101 Firefox/59.0" "-"

它重定向到/ login,它应该实际上:

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter
{
    @Autowired private AuthService authService;

    @Override
    protected void configure(HttpSecurity http) throws Exception
    {
        http
            .authorizeRequests()
            .anyRequest().authenticated()
        .and()
            .formLogin()
            .loginPage("/login")
            .permitAll()
        .and()
            .logout()
            .permitAll();

        http.csrf().disable();
    }

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception
    {
        auth.userDetailsService(authService);
    }
}

有人能告诉我为什么对/ login的调用似乎被重定向到/ login而不是在该URL上撤回页面?

谢谢你的帮助!

1 回答

  • 1

    你应该使用:

    proxy_pass http://tomcat;
    

    用于在端口8080上连接到Tomcat的协议方案是固定的,应该是 httphttps . 这个 server 块的 $scheme 碰巧是 http ,但是没有充分的理由将该变量用于代理连接 .

    默认情况下, nginx 将透明地将请求的URI传递给代理连接,因此除非必须更改某些内容,否则无需在 proxy_pass 语句上提供URI .

    当存在URL编码字符时(例如在登录序列中将登录页面作为参数传递),使用 $request_uri 是有问题的,因为它是原始请求并且字符尚未被解码 . proxy_pass 指令可能会编码已编码的字符,将请求变为垃圾 .

    有关更多信息,请参阅this document .

相关问题