Nginx反向代理https请求个别文件报错400 Bad Request

Linux
Nginx反向代理https请求个别文件报错400 Bad Request-下一朵云

一、问题描述

Nginx反向代理容器里边的服务,可以正常打开,但是测试发现通过https请求某个文件时会返回400 Bad Request错误。如图1 ,请求/json时就会报错400 Bad Request。

Nginx反向代理https请求个别文件报错400 Bad Request-下一朵云
图1 400 Bad Request

系统环境:

  • CentOS Linux release 7.9.2009 (Core)
  • Docker version 1.13.1, build 7d71120/1.13.1
  • nginx version: nginx/1.22.0

Nginx反代配置文件:

其中8443是容器映射出来的端口,容器和Nginx都在同一台机器。

 server {
        listen       443 ssl;
        server_name  saopigu.cn;

        access_log  logs/01.log  main;
        error_log  logs/01error.log;

        ssl_certificate      cert01.pem;
        ssl_certificate_key  cert01.key;

        ssl_session_cache    shared:SSL:1m;
        ssl_session_timeout  5m;
        ssl_ciphers  HIGH:!aNULL:!MD5;
        ssl_prefer_server_ciphers  on;

        add_header Strict-Transport-Security "max-age=15768000; includeSubDomains; preload" always;

        location / {
             proxy_pass https://127.0.0.1:8443;
             proxy_set_header Host $http_host;
             client_max_body_size 4096m;
         }
  }

二、问题解决

测试直接访问容器的8443端口没有这个报错,只有通过反代的时候才会报错,在网上搜索了各种Nginx反代报错400的文章都无法解决,分析请求和响应的内容,应该是反代后cookie的问题导致的。

解决办法:

proxy_pass设置为宿主机的IP

Nginx配置文件如下:

 location / {
             proxy_pass https://192.168.110.231:8443;
             proxy_set_header Host $http_host;
             client_max_body_size 4096m;
         }

修改配置后,恢复正常,如图2

Nginx反向代理https请求个别文件报错400 Bad Request-下一朵云
图2 200 OK

为什么会出现这个问题,原理暂时还没搞清楚,还请技术大佬在评论区多多指教!

三、优化配置( *非必要,可以不配置 )

如果宿主机的IP会有变动,代理的容器又较多,手动修改每个反代的配置就会很愚蠢,所以有个更好的解决办法。

vi /etc/hosts

添加一行

192.168.110.231 proxylocalhost

此时修改Nginx配置文件:

 location / {
             proxy_pass https://proxylocalhost:8443;
             proxy_set_header Host $http_host;
             client_max_body_size 4096m;
         }

宿主机IP变动时,只需要修改一下hosts文件即可。