Nginx路由

NGINX 可以根据多种请求字段进行路由,包括:

  • $scheme:请求协议 (http 或 https)。

  • $host:请求主机名。

  • $remote_addr:请求方的 IP 地址。

  • $remote_port:请求方的端口。

  • $request_uri:请求的 URI。

  • $request_method:请求方法 (GET, POST, PUT 等)。

  • $http_*:请求中的 HTTP 头字段,例如:$http_user_agent、$http_accept_encoding 等。

  • $args:请求参数。

  • $content_type:请求的内容类型。

  • $is_args:是否存在请求参数。 以上这些字段可以在 NGINX 中通过使用 map 指令来使用,并将其映射到不同的代理后端。

基于user_agent路由的示例

http {
    map $http_user_agent $backend {
        default "default_backend";
        ~*Android.* "android_backend";
        ~*iPad.* "ipad_backend";
        ~*iPhone.* "iphone_backend";
    }

    server {
        listen 80;

        location / {
            proxy_pass http://$backend;
        }
    }

    upstream default_backend {
        server backend1.example.com;
    }

    upstream android_backend {
        server backend2.example.com;
    }

    upstream ipad_backend {
        server backend3.example.com;
    }

    upstream iphone_backend {
        server backend4.example.com;
    }
}

基于accept路由的示例

http {
    map $http_accept $backend {
        default "default_backend";
        ~*application/json.* "json_backend";
        ~*application/xml.* "xml_backend";
    }

    server {
        listen 80;

        location / {
            proxy_pass http://$backend;
        }
    }

    upstream default_backend {
        server backend1.example.com;
    }

    upstream json_backend {
        server backend2.example.com;
    }

    upstream xml_backend {
        server backend3.example.com;
    }
}

最后更新于