一、问题描述
使用nginx 进行反向代理到服务端,在使用两个及以上nginx 进行请求处理时,nginx端口和服务端口不一致时;
服务内部进行请求重定向,会导致最后返回的响应头中的,端口使用的是服务的端口;
查看响应头可以发现,Location 值,端口使用的是服务的端口;
如下图:
二、解决方案
1.端口修改一致
如上图,所示因为端口改变导致,因此我们在整个请求链中,使用的端口改为一致即可(仅适合,单点部署项目以及nginx 和 端口 可以任意改动)
2.修改响应头
使用nginx headers-more-nginx-module 模块自定义响应头;
附带Dockerfile
#基准镜像
FROM alpine:3.16
#作者信息
MAINTAINER "kongbai"
#工作目录
WORKDIR /usr/local/src/
#定义环境变量
ENV NG_VERSION nginx-1.21.0
#下载nginx文件并解压
RUN wget http://nginx.org/download/$NG_VERSION.tar.gz && tar xzvf $NG_VERSION.tar.gz
#更新Alpine的软件源为阿里云,因为从默认官源拉取实在太慢了
RUN echo http://mirrors.aliyun.com/alpine/v3.10/main/ > /etc/apk/repositories && \
echo http://mirrors.aliyun.com/alpine/v3.10/community/ >> /etc/apk/repositories
RUN apk update && apk upgrade
#安装编译依赖包
RUN apk add --no-cache --virtual .build-deps gcc libc-dev make openssl-dev pcre-dev zlib-dev linux-headers curl gnupg libxslt-dev gd-dev geoip-dev
RUN mkdir -p /usr/local/nginx/
ADD headers-more-nginx-module-master.zip /usr/local/nginx/.
RUN apk --no-cache add unzip zip
RUN cd /usr/local/nginx/ && unzip headers-more-nginx-module-master.zip
#切换工作目录
WORKDIR /usr/local/src/$NG_VERSION
#编译安装nginx
RUN ./configure --prefix=/usr/local/nginx --with-file-aio --with-http_ssl_module --with-http_realip_module --with-http_addition_module --with-http_xslt_module --with-http_image_filter_module --with-http_geoip_module --with-http_sub_module --with-http_dav_module --with-http_flv_module --with-http_mp4_module --with-http_gunzip_module --with-http_gzip_static_module --with-http_auth_request_module --with-http_random_index_module --with-http_secure_link_module --with-http_degradation_module --with-http_stub_status_module --add-module=/usr/local/nginx/headers-more-nginx-module-master && make && make install
#设置sbin环境变量
ENV PATH /usr/local/nginx/sbin:$PATH
EXPOSE 80
CMD ["-g","daemon off;"]
最后nginx配置
http {
include /usr/local/src/nginx-1.21.0/conf/mime.types;
default_type application/octet-stream;
sendfile on;
keepalive_timeout 65;
client_body_buffer_size 1024m;
map $upstream_http_Location $location{
~http://**:31000/(?<param>.*) https://**:32000/$param;
# 默认情况,保持原状
default $upstream_http_Location;
}
server {
listen 31000;
server_name localhost;
location / {
proxy_pass http://*:8888;
proxy_set_header Host $host:$server_port;
proxy_set_header REMOTE-HOST $remote_addr;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_redirect off;
more_set_headers -s '301 302' 'Location $location';
client_max_body_size 1024m;
}
}
}