Nginx的rewrite和proxypass的写法

Published: Tags: NGINX LINUX

整个URL重写(适用于整个域名用作API调用等情况)

    location / {
        include        fastcgi.conf;
        fastcgi_pass   127.0.0.1:9001;
        rewrite  ^/(.*)$  /gateway.php?api=$1  break;
    }

部分URL重写(适用于API分版本、或子路径等情况)

    location /openapi/ {
        root           /data/web;
        include        fastcgi_params;
        fastcgi_pass   127.0.0.1:9000;
        fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
        rewrite        ^/openapi/(.*)$  /openapi/gateway.php?api=$1  break;
    }

转发请求(适用于分离相同域名的API请求,到其他域名的服务器上)

    location /api/ {
        proxy_pass        https://dev.example.com;
        proxy_set_header  X-Forwarded-Proto  $scheme;
        proxy_set_header  Host               $http_host;
        proxy_set_header  X-Real-IP          $remote_addr;
    }