Home > front end >  How can I add header every location if query exist Nginx
How can I add header every location if query exist Nginx

Time:04-06

I have two url

http://localhost/?shop=test

http://localhost/login?shop=test

first url is working. But second url coming 404 nginx page. how can I fix this problem. I want to every location come header if exist shop query

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

CodePudding user response:

The problem with using if inside a location, is that it doesn't work the way you expect.

You can use a map to define the value of the add_header directive. If the argument is missing or empty, the header will not be added.

For example:

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

    add_header Content-Security-Policy $csp;

    location / {
        ...
    }
}

CodePudding user response:

I fixed like that

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