简单的例子

  1. server {
  2. listen 80;
  3. location / {
  4. proxy_pass http://192.168.0.20:80;
  5. }
  6. }

支持多站点的例子

  1. server {
  2. listen 80;
  3. location / {
  4. proxy_set_header Host $host;
  5. proxy_pass http://192.168.0.20:80;
  6. }
  7. }

根据 location 转发到不同的服务器

当 proxy_pass 地址不带 URI 时,用户请求 URI 会原封不动地发送到后端。

  1. server {
  2. listen 80;
  3. # /foo/index.html -> http://foo.com/foo/index.html
  4. location /foo/ {
  5. proxy_set_header Host foo.com;
  6. proxy_pass http://192.168.0.20:80;
  7. }
  8. # /bar/index.html -> http://bar.com/bar/index.html
  9. location ~ /bar/ {
  10. proxy_pass http://bar.com:80;
  11. }
  12. }

当 proxy_pass 地址带上 URI时,用户请求 URI 中与 Location 所匹配的部分会被替换成 proxy_pass 的 URI。

  1. server {
  2. listen 80;
  3. # /foo/index.html -> http://foo.com/index.html
  4. # /foo/ replace with /
  5. location /foo/ {
  6. proxy_set_header Host foo.com;
  7. proxy_pass http://192.168.0.20:80/;
  8. }
  9. # /bar/me/index.html -> http://bar.com/bar-website/me/index.html
  10. # /bar/ replace with /bar-website/
  11. location /bar/ {
  12. proxy_pass http://bar.com:80/bar-website/;
  13. }
  14. }

If the proxy_pass directive 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 的方式分派请求。

  1. upstream foo {
  2. server 192.168.0.10:80;
  3. server 192.168.0.20:80;
  4. }
  5. server {
  6. listen 80;
  7. server_name foo.com;
  8. location / {
  9. proxy_set_header Host $http_host;
  10. proxy_set_header X-Real-IP $remote_addr;
  11. proxy_set_header X-Forwarded-Proto $scheme;
  12. proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
  13. proxy_pass http://foo;
  14. }
  15. }

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 resolvermore