官方文档 http://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_pass
文章目录
配置语法
Syntax: proxy_pass URL;
Default: —
Context: location, if in location, limit_except
URL配置规则
url用于设置代理服务器的协议和地址,以及可选的uri。
一般表现形式为:protocol://ip:port[uri]
或者 protocol://domain[uri]
由于URL末尾是否存在uri的处理逻辑不同,下面着重分析:
URL末尾是否存在 uri 的区别
1. URL末尾存在 uri
“
/
” 也算是uri
处理逻辑:代理请求时,会先将请求的uri中和location匹配的部分替换成 proxy_pass 指定的uri,再将最终的uri拼接到代理地址,才是最终访问的url
举个栗子:
有如下配置:
location /proxy {
proxy_pass http://127.0.0.1:8099/svr1; # uri为'/svr1'
}
有如下请求:http://localhost:8088/proxy/index.html
详细解析:
- 请求的uri:/proxy/index.html
- location匹配的部分:/proxy
- proxy_pass 指定的uri:/svr1
- 最终的uri:/svr1/index.html (将请求的uri中和location匹配的部分替换成 proxy_pass 指定的uri)
- 代理地址:http://127.0.0.1:8099
- 最终访问的url:http://127.0.0.1:8099/svr1/index.html
即访问 http://localhost:8088/proxy/index.html,实际请求路径为 http://127.0.0.1:8099/svr1/index.html
2. URL末尾不存在 uri
处理逻辑:代理请求时,直接将请求的uri拼接到代理地址,就是最终访问的url
举个栗子:
有如下配置:
location /proxy2 {
proxy_pass http://127.0.0.1:8099; # 无uri
}
有如下请求:http://localhost:8088/proxy2/index.html
详细解析:
- 请求的uri:/proxy2/index.html
- 代理地址:http://127.0.0.1:8099
- 最终访问的url:http://127.0.0.1:8099/proxy2/index.html
即访问 http://localhost:8088/proxy2/index.html,实际请求路径为 http://127.0.0.1:8099/proxy2/index.html
扩展:通过 rewrite 配置修改代理路径
location /v1 {
proxy_pass http://127.0.0.1:8099; # 无uri
rewrite '^/v1/(.*)$' /$1 break;
}
即访问 http://localhost:8088/v1/index.html,实际请求路径为 http://127.0.0.1:8099/index.html
附上测试用的nginx.conf
events {
worker_connections 1024;
}
http {
server {
listen 8088;
server_name localhost;
location /proxy {
proxy_pass http://127.0.0.1:8099/svr1; # uri为'/svr1'
}
location /proxy2 {
proxy_pass http://127.0.0.1:8099; # 无uri
}
location /v1 {
proxy_pass http://127.0.0.1:8099;
rewrite '^/v1/(.*)$' /$1 break;
}
location /v2 {
proxy_pass http://127.0.0.1:8099$1;
}
location /v3 {
proxy_pass http://127.0.0.1:8099$request_uri;
}
location ~ /v4/([\d]+)/(.*) {
proxy_pass http://127.0.0.1:$1/$2?$query_string;
}
location ~ /v5/([\d]+) {
proxy_pass http://127.0.0.1:$1;
rewrite ^/v5/([\d]+)/(.*)$ /$2 break;
}
location /v6 {
if ($request_uri ~* ^/(.*)$) {
proxy_pass http://127.0.0.1:8099/$1;
}
}
}
# 此server模拟被代理的服务。
server {
listen 8099;
server_name localhost;
location / {
add_header request $request;
# 直接返回请求路径。也就是通过Nginx代理后,实际请求的url。
default_type text/html; return 200 $host:$server_port$request_uri;
}
}
}
end