大网数据广告活动
服务器运维问答

Override CSP header for specific location

· 52CE 我爱测

I have an nginx config that includes a CSP header that is served for all requests. Now I need to override it in one particular location (that also happens to be rewritten). I'm thinking something like this: server { listen 80; li…

问题原文

原帖链接 · Synchro · CC BY-SA 3.0

I have an nginx config that includes a CSP header that is served for all requests. Now I need to override it in one particular location (that also happens to be rewritten). I'm thinking something like this:

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

However, while that sets the header on any request starting with /special, it results in a 404 because it doesn't continue to the following location that maps PHP files. How should I do this?

已采纳解答

原帖链接 · gxx · CC BY-SA 3.0

Try to the see if the following works for you:

http context:

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 context:

add_header Content-Security-Policy $csp_header;

摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。

资料来源与适用范围

资料来源
Server Fault
适用范围
以原帖系统、软件版本与发布日期为准(2017-08-25)
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 3.0

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。