Nginx 配置可重用块

Nginx config re-usable blocks

我像这样将 Nginx 配置为某些应用程序服务器的反向代理,但那里有很多重复代码(proxy_pass 行除外)。有什么方法可以将 proxy_redirect 和 proxy_set_header 行移动到某个公共块中,并只为每个位置块引用它?

Nginx.conf:

location ^~ /users {
            proxy_pass http://192.168.0.1:5001;
            proxy_redirect http://api.example.com https://api.example.com;
            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header X-Forwarded-Proto https;
}

location ^~ /users/verify {
            proxy_pass http://192.168.0.1:5002;
            proxy_redirect http://api.example.com https://api.example.com;
            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header X-Forwarded-Proto https;
}

当然可以。您可以在配置的 http 块中执行此操作,如下所示:

http {
    include       /etc/nginx/mime.types;
    default_type  application/octet-stream;

    log_format    main  '$remote_addr - $remote_user [$time_local] "$request" '
                  '$status $body_bytes_sent "$http_referer" '
                  '"$http_user_agent" "$http_x_forwarded_for"';

    #Rest of your config

    #Proxy settings
    proxy_redirect http://api.example.com https://api.example.com;
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header X-Forwarded-Proto https;

    include /etc/nginx/conf.d/*.conf;
}

请注意,这些设置将是 "global"。