proxy_pass
Nginx的proxy_pass将请求代理到其他的后端服务器。例如
listen 9999;
server_name wyc.com;
location /test/aaa {
content_by_lua_block {
ngx.say('new:9999/test/aaa')
}
}
location /test/aaa/bbb {
content_by_lua_block {
ngx.say('new:9999/test/aaa/bbb')
}
}
location /ttt {
proxy_pass http://wyc.com:9999/test;
}
- 请求
http://wychao.com:8888/user/wyc/wyc/aaa?aa=11&bb=22
(匹配到域名和端口和对应的location为/user/wyc,然后将后面的/wyc/aaa?aa=11&bb=22proxy_pass到需要代理到的服务,正好匹配到另一个server的location里)
server {
server_name wychao.com;
listen 8888;
location /user/wyc {
proxy_pass http://aaa.wyc.com:8888/user;
}
location = /user/name {
echo $request_uri;
}
}
server {
server_name aaa.wyc.com;
listen 8888;
location /user/wyc {
echo $request_uri;
}
}
aaa.com/aa/bb?a=1 | /aa | http://bbb.com/cc | http://bbb.com/cc/bb?a=1 |
- 即最终代理到的url:将请求的uri去掉匹配到的location部分,其余部分拼接到proxy_pass后面,包括query_string部分。
upstream
upstream可以做简单的负载均衡等,下面以百度为例,upstream在http段,
upstream search {
server 180.149.132.47;
}
server {
# List port
listen 8888;
server_name wyc.com;
location /s {
#add_header 'Access-Control-Allow-Credentials' 'true';
proxy_redirect off;
proxy_set_header Host "www.baidu.com";
proxy_set_header X-Real-Ip $remote_addr;
proxy_set_header X-Forwarded-for $remote_addr;
proxy_pass http://search;
}
}
上面请求域名wyc.com,端口8888,location将代理到search的upstream中,访问:
http://wyc.com:8888/s?wd=nba
和
http://baidu.com/s?wd=nba
的结果是一样的
upstream支持多种负载均衡,下面一个最简单的根据权重分配:
#server1:
server {
server_name wwyycc.com;
listen 8888;
location /user {
content_by_lua_block {
ngx.say('wwyycc.com:host')
}
}
}
#server2:
server {
server_name wwyycc.com;
listen 9999;
location /user {
echo "user wwyycc user";
}
}
#负载:server3:server_name:wyc.com 端口:8888
upstream manageserver {
server wwyycc.com:8888 weight=2;
server wwyycc.com:9999;
}
location /user {
#add_header 'Access-Control-Allow-Credentials' 'true';
proxy_redirect off;
proxy_set_header Host "wwyycc.com";
proxy_set_header X-Real-Ip $remote_addr;
proxy_set_header X-Forwarded-for $remote_addr;
proxy_pass http://manageserver;
}