如何配置 nginx 位置以共享常用配置选项?

net*_*ain 51 nginx

如何为一组位置配置共享配置块?

    location / {

            proxy_pass        http://127.0.0.1:9000/;
            proxy_redirect    off;
            proxy_set_header  Host             $http_host;
            proxy_set_header  X-Real-IP        $remote_addr;
            proxy_set_header  X-Forwarded-For  $proxy_add_x_forwarded_for;

            proxy_cache cache-test;
            proxy_cache_valid 200 302 24h;
            proxy_cache_valid 404 60s;
            add_header X-Cache-Status $upstream_cache_status;

    }


    location /api/0.1/user{
            proxy_cache_key /user/$http_authorization;
    }
Run Code Online (Sandbox Code Playgroud)

现在,如果我尝试访问 /api/0.1/user 然后我会得到 404 因为它没有将请求传递给 127.0.0.1:9000

小智 65

创建一个通用代理配置并根据需要包含。

/etc/nginx/api_proxy.conf

proxy_pass        http://127.0.0.1:9000/;
proxy_redirect    off;
proxy_set_header  Host             $http_host;
proxy_set_header  X-Real-IP        $remote_addr;
proxy_set_header  X-Forwarded-For  $proxy_add_x_forwarded_for;

proxy_cache cache-test;
proxy_cache_valid 200 302 24h;
proxy_cache_valid 404 60s;
add_header X-Cache-Status $upstream_cache_status;
Run Code Online (Sandbox Code Playgroud)

您的主机配置文件

...
location /api/0.1/user {
    include /etc/nginx/api_proxy.conf;
    proxy_cache_key /user/$http_authorization;
}
...
Run Code Online (Sandbox Code Playgroud)

  • +1,但只有一个注意事项:事实证明,您可以通过这种方式包含一大堆配置,包括整个位置 http://nginx.org/en/docs/ngx_core_module.html#include (2认同)

Vad*_*dar 12

大多数 proxy_* 配置变量也允许在服务器上下文中使用,因此您可以将它们向上移动以在多个位置共享相同的设置。

但是,proxy_pass 应该只在 location 内使用。所以你应该在每个位置至少有这个指令,可以选择覆盖一些额外的 proxy_* 变量的值。

  • 如果您有特定于位置的 `proxy_set_header` 指令,这将不起作用,因为“当且仅当当前级别上没有定义 proxy_set_header 指令时,这些指令才从上一级继承。” http://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_set_header (3认同)