将一个请求打到被代理的服务器
在location里面使用proxy_pass指令来指定代理的地址,地址可以包含端口号。
-
例如:
location /some/path/ { proxy_pass http://www.example.com/link/; } location ~ \.php { proxy_pass http://127.0.0.1:8000; }
注意下第一个例子,如果代理的地址包含一个uri,/link/。它将会替换请求的uri中匹配location参数的那部分
如果请求是/some/path/page.html,uri则会被代理成:
http://www.example.com/link/page.html
。如果代理的地址没有uri,那么将整个uri传递过来。
-
将请求打到非http服务:
-
fastcgi_pass
把请求打到FastCGI服务器 -
uwsgi_pass
uwsgi服务器 -
scgi_pass
SCGI服务器 -
memcached_pass
memcached 服务器
-
传递请求头
默认的,nginx重新定义两个header,"Host"和"Connection",并且排除掉值为空的header。"Host"的值是$proxy_host变量的值,"Connection"设置成close。
使用proxy_set_header来改变header,这个指令可以放到location或者更高的层级,它也可以在特定的server context或者http块中指定。
-
如:
location /some/path/ { proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_pass http://localhost:8000; }
-
如果不想让某个header传给被代理的服务器,将其置空。
location /some/path/ { proxy_set_header Accept-Encoding ""; proxy_pass http://localhost:8000; }
选择出口IP
代理服务器可能有多个ip地址,对于一个特定的被代理的server可以选择一个特定的ip地址。
使用
proxy_bind
来指定ip地址。ip地址也可以使用变量,如$server_addr,指定的是接受请求的那个ip-
例子:
location /app1/ { proxy_bind 127.0.0.1; proxy_pass http://example.com/app1/; } location /app2/ { proxy_bind 127.0.0.2; proxy_pass http://example.com/app2/; } location /app3/ { proxy_bind $server_addr; proxy_pass http://example.com/app3/; }