如果查询存在 Nginx,如何在每个位置添加 header

How can I add header every location if query exist Nginx

我有两个url

http://localhost/?shop=test

http:///localhost/login?shop=test

第一个 url 正在工作。但是第二个 url 即将到来的 404 nginx 页面。我该如何解决这个问题。我想每个位置都来 header 如果存在商店查询

server {
        listen 8081 default_server;
        listen [::]:8081 default_server;

        server_name _;

        location / {
                if ( $arg_shop ) {
                        add_header Content-Security-Policy "frame-ancestors https://$arg_shop";
                }
                root /home;
                index index.html;
                include  /etc/nginx/mime.types;
                try_files $uri $uri/ /index.html?$query_string;
        }
}

我就这样修好了

server {
        listen 8081 default_server;
        listen [::]:8081 default_server;

        server_name _;

        location / {
                error_page 404 = @error_page;

                if ( $arg_shop ) {
                        add_header "Content-Security-Policy" "frame-ancestors https://$arg_shop";
                }

                root /home;
                index index.html;
                include  /etc/nginx/mime.types;
                try_files $uri $uri/ /index.html?$query_string;
        }

        location @error_page {
                add_header "Content-Security-Policy" "frame-ancestors https://$arg_shop";
                root /home;
                index index.html;
                include  /etc/nginx/mime.types;
                try_files $uri $uri/ /index.html?$query_string;
        }
}

location 中使用 if 的问题是 it doesn't work the way you expect.

您可以use a map定义add_header指令的值。如果参数缺失或为空,则不会添加 header。

例如:

map $arg_shop $csp {
    ""      "";
    default "frame-ancestors https://$arg_shop";
}
server {
    ...

    add_header Content-Security-Policy $csp;

    location / {
        ...
    }
}