'How can I add header every location if query exist Nginx
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;
}
}
Solution 1:[1]
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 / {
...
}
}
Solution 2:[2]
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;
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Richard Smith |
| Solution 2 | Erdem Ün |
