如果查询存在,我该如何在每个位置添加标头 Nginx

3
我有两个URL:
1. http://localhost/?shop=test 2. http://localhost/login?shop=test
第一个URL可以正常工作,但是第二个URL会出现404 Nginx页面。我该如何解决这个问题?我希望在所有位置中,如果存在“shop”查询,则将其添加到头部。
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;
        }
}

不要在location中使用if它的工作方式与您期望的不同。尝试将if块移动到server块的上一级。 - Richard Smith
@RichardSmith,你能回答一下吗?我不是完全理解。 - Erdem Ün
2个回答

3
location中使用if的问题在于,它不会按照您预期的方式工作
您可以使用map来定义add_header指令的值。如果参数缺失或为空,则不会添加标头。
例如:
map $arg_shop $csp {
    ""      "";
    default "frame-ancestors https://$arg_shop";
}
server {
    ...

    add_header Content-Security-Policy $csp;

    location / {
        ...
    }
}

它的工作方式非常健康。谢谢。 - Erdem Ün

0

我已经修复了

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;
        }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接