简单的例子
server {listen 80;location / {proxy_pass http://192.168.0.20:80;}}
支持多站点的例子
server {listen 80;location / {proxy_set_header Host $host;proxy_pass http://192.168.0.20:80;}}
根据 location 转发到不同的服务器
当 proxy_pass 地址不带 URI 时,用户请求 URI 会原封不动地发送到后端。
server {listen 80;# /foo/index.html -> http://foo.com/foo/index.htmllocation /foo/ {proxy_set_header Host foo.com;proxy_pass http://192.168.0.20:80;}# /bar/index.html -> http://bar.com/bar/index.htmllocation ~ /bar/ {proxy_pass http://bar.com:80;}}
当 proxy_pass 地址带上 URI时,用户请求 URI 中与 Location 所匹配的部分会被替换成 proxy_pass 的 URI。
server {listen 80;# /foo/index.html -> http://foo.com/index.html# /foo/ replace with /location /foo/ {proxy_set_header Host foo.com;proxy_pass http://192.168.0.20:80/;}# /bar/me/index.html -> http://bar.com/bar-website/me/index.html# /bar/ replace with /bar-website/location /bar/ {proxy_pass http://bar.com:80/bar-website/;}}
If the
proxy_passdirective is specified with a URI, then when a request is passed to the server, the part of a normalized request URI matching the location is replaced by a URI specified in the directive… more
后端服务器组
代理到的后端服务器可以有多台,此时使用服务器组,Nginx 默认采用 round-robin 的方式分派请求。
upstream foo {server 192.168.0.10:80;server 192.168.0.20:80;}server {listen 80;server_name foo.com;location / {proxy_set_header Host $http_host;proxy_set_header X-Real-IP $remote_addr;proxy_set_header X-Forwarded-Proto $scheme;proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;proxy_pass http://foo;}}
Parameter value can contain variables. In this case, if an address is specified as a domain name, the name is searched among the described server groups, and, if not found, is determined using a resolver… more
