一、location配置请求转发
根据Nginx的官方文档,Location标签包含以下修饰符,分别是:
(1) =:表示完全匹配;
#nginx配置
location = /11 {
return 400;
}
location = /11/22 {
return 401;
}
浏览器输入:http://ip:port/11/
返回:400
浏览器输入:http://ip:port/11/22
返回:401
浏览器输入:http://ip:port/11/22/33
返回:An error occurred.Sorry, the page you are looking for is currently unavailable.
Please try again later.
(2) ^~:匹配URI的前缀,匹配最长的规则;
#nginx配置
location ^~ /11 {
return 400;
}
location ^~ /11/22 {
return 401;
}
浏览器输入:http://ip:port/11/
返回:400
浏览器输入:http://ip:port/11/22
返回:401
浏览器输入:http://ip:port/11/22/33
返回:401
(3) ~:匹配正则表达式,大小写敏感,匹配最先出现的规则;
#nginx配置
location ~ /aa {
return 400;
}
location ~ /aa/bb {
return 401;
}
浏览器输入:http://ip:port/aa/
返回:400
浏览器输入:http://ip:port/aa/bb
返回:400
浏览器输入:http://ip:port/aA
返回:404 Not Found
(4) ~*:匹配正则表达式,大小写不敏感,匹配最先出现的规则;
#nginx配置
location ~* /aa {
return 400;
}
location ~* /aa/bb {
return 401;
}
浏览器输入:http://ip:port/aa/
返回:400
浏览器输入:http://ip:port/aa/bb
返回:400
浏览器输入:http://ip:port/aA
返回:400
(5) /:通用匹配,匹配最长的规则。
#nginx配置
location /11 {
return 400;
}
location /11/22 {
return 401;
}
浏览器输入:http://ip:port/11/
返回:400
浏览器输入:http://ip:port/11/22
返回:401
浏览器输入:http://ip:port/11/22/33
返回:401
优先级:(1)> (2) > (3) = (4) > (5)
完全匹配的优先级最高,其次是路径匹配,然后是正则匹配,最后是通用匹配。
nginx接受request请求后,先判断该请求属于哪一个优先级。确认好优先级后按照各优先级内匹配规则进行判断。
二、目标地址不带根路径转发
#去除匹配地址,原请求:http://ip:port/test-hz;转发后请求:http://10.48.1.203:3089
location ^~ /test-hz {
rewrite ^/test-hz$ / break;
proxy_pass http://10.48.1.203:3089;
}
语法:rewrite regex replacement [flag];
regex:正则^/test-hz$
replacement:表示需要替换的地址/
flag:控制符break
三、upstream配置
注意:upstream 不能包含'_'符号
四、Connection reset by peer
nginx报错:
2025/03/28 10:49:44 [error] 10556#0: *373536121 readv() failed (104: Connection reset by peer) while reading upstream, client: 10.16.1.23, server: localhost, request: "POST /test-hz HTTP/1.1", upstream: "http://188.48.10.20:3089/", host: "10.16.1.14:8000"
注意:该日志为nginx中接受请求的日志,非请求外部的日志。HTTP/1.1版本表示请求方使用的协议版本。
应用程序报错:
Caused by: org.apache.http.ConnectionClosedException: Premature end of chunk coded message body: closing chunk expected
客户端读取响应信息时,服务端发送reset包导致链接重置,客户端无法接口完整数据包导致接口报错。从应用程序的报错看分块数据传输未完成链接断开了。
1.服务端处理,找到rst原因;
2.客户端处理,nginx设置http协议为1.1版本(长连接,支持大消息分块传输)(默认1.0),增加请求头信息keep-alive。
location ^~ /test-hz {
rewrite ^/test-hz$ / break;
proxy_pass http://10.48.1.203:3089;#proxy_set_header Connection $http_connection; # 透传客户端值
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header Connection "keep-alive";# 强制长连接
}