记录一次错误error:1035 connect() failed (111: Connection refused) while connecting to upstream, client: ...217, server: .com, request: “POST /api/userLogin HTTP/1.1”, upstream: "http://.1:8443/userLogin", host: "*.com"。
一、起因
该项目的部署是在腾讯云服务器上,http升级为https,使用的是腾讯ssl证书,阿里的域名,在nginx.conf配置过程中,出现前端向后端发送请求失败问题。出现以下错误:
nginx.conf配置如下:
server{
#SSL 默认访问端口号为 443
listen 443 ssl;
server_name 域名;
default_type text/html;
ssl_certificate 证书文件路径(.crt/.pem);
ssl_certificate_key 私钥文件路径(.key);
ssl_session_timeout 5m;
#请按照以下协议配置
ssl_protocols TLSv1.2 TLSv1.3;
s#请按照以下套件配置,配置加密套件,写法遵循 openssl 标准。
ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:HIGH:!aNULL:!MD5:!RC4:!DHE;
ssl_prefer_server_ciphers on;
location / {
root /usr/share/nginx/html/dist/;
try_files $uri $uri/ /index.html;
index index.html;
}
location /api/ {
default_type application/json;
proxy_pass http://localhost:8443/;
}
}
二、解决办法
在nginx.conf配置中增加一条: proxy_set_header Host $http_host;
server{
#SSL 默认访问端口号为 443
listen 443 ssl;
server_name 域名;
default_type text/html;
ssl_certificate 证书文件路径(.crt/.pem);
ssl_certificate_key 私钥文件路径(.key);
ssl_session_timeout 5m;
#请按照以下协议配置
ssl_protocols TLSv1.2 TLSv1.3;
s#请按照以下套件配置,配置加密套件,写法遵循 openssl 标准。
ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:HIGH:!aNULL:!MD5:!RC4:!DHE;
ssl_prefer_server_ciphers on;
location / {
root /usr/share/nginx/html/dist/;
try_files $uri $uri/ /index.html;
index index.html;
}
location /api/ {
# nginx反向代理重写请求头中的host字段属性
proxy_set_header Host $http_host;
default_type application/json;
proxy_pass http://localhost:8443/;
}
}
三、分析
3.1 nginx中proxy_set_header Host $host的作用
nginx为了实现反向代理的需求而增加了一个ngx_http_proxy_module模块。其中proxy_set_header指令就是该模块需要读取的配置文件。在这里,所有设置的值的含义和http请求体中的含义完全相同,除了Host外还有X-Forward-For。
Host的含义是表明请求的主机名,因为nginx作为反向代理使用,而如果后端真实服务器设置有类似防盗链或者根据http请求头中的host字段来进行路由或判断功能的话,如果反向代理层的nginx不重写请求头中的host字段,将会导致请求失败【默认反向代理服务器会向后端真实服务器发送请求,并且请求头中的host字段应为proxy_pass指令设置的服务器】