我有一个 nginx 配置,其中包含一个用于所有请求的 CSP 标头。现在我需要在一个特定位置覆盖它(也恰好被重写)。我在想这样的事情:
server {
listen 80;
listen [::]:80;
server_name example.com;
root /var/www;
index index.php;
try_files $uri @rewrites;
add_header Content-Security-Policy "default-src 'self' ; script-src 'self' ; style-src 'self' 'unsafe-inline' ; img-src * 'self' data: ; font-src 'self' ; media-src * 'self' ; form-action 'self'";
location @rewrites {
rewrite ^/special/([0-9]*) /special.php?id=$1 last;
rewrite ^/foo/([a-z]+) /foo.php?method=$1 last;
}
location /special {
add_header Content-Security-Policy "default-src 'self' ; script-src 'self' 'unsafe-inline' ; style-src 'self' 'unsafe-inline' ; img-src * 'self' data: ; font-src 'self' ; media-src * 'self' ; form-action 'self'";
}
location ~ \.php$ {
try_files $uri =404;
fastcgi_split_path_info ^(.+?\.php)(/.*)$;
include fastcgi_params;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_pass php;
}
}
但是,虽然这会在任何以 开头的请求上设置标头/special
,但它会导致 404,因为它不会继续到映射 PHP 文件的以下位置。我该怎么做?
答案1
尝试以下方法看看是否适合您:
http
语境:
map $request_uri $csp_header {
default "default-src 'self' ; script-src 'self' ; style-src 'self' 'unsafe-inline' ; img-src * 'self' data: ; font-src 'self' ; media-src * 'self' ; form-action 'self'";
"~^/special" "default-src 'self' ; script-src 'self' 'unsafe-inline' ; style-src 'self' 'unsafe-inline' ; img-src * 'self' data: ; font-src 'self' ; media-src * 'self' ; form-action 'self'";
}
server
语境:
add_header Content-Security-Policy $csp_header;