Nginx proxy_pass指令(代理配置)

官方文档 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

  • 2
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值