nginx 设置 Content-Security-Policy
时间: 2023-10-31 10:36:22 浏览: 391
可以在 nginx 配置文件中添加以下指令来设置 Content-Security-Policy:
add_header Content-Security-Policy "directive1; directive2; ...";
其中 directive1、directive2 等为 Content-Security-Policy 指令。常见的指令包括:
default-src:指定默认允许加载资源的来源;
script-src:指定允许加载 JavaScript 的来源;
style-src:指定允许加载 CSS 的来源;
img-src:指定允许加载图片的来源;
font-src:指定允许加载字体的来源;
等等。
详细的指令及用法可以参考 Content Security Policy Level 3 Specification。
相关问题
nginx配置Content-Security-Policy
Nginx的Content-Security-Policy (CSP) 配置允许网站管理员控制页面上可以加载的内容来源,以增强网页安全性和防止跨站脚本攻击。要在Nginx中启用CSP,你需要在服务器块(server block)的`http`或`location`上下文中添加`content-security-policy`指令。下面是一个基本的例子:
```nginx
server {
listen 80;
server_name yourdomain.com;
# 设置默认的Content Security Policy
add_header Content-Security-Policy "default-src 'self';
script-src 'self' https://ajax.googleapis.com;
style-src 'self' 'unsafe-inline';
img-src 'self' data:;";
# 如果有需要针对特定URL路径设置更详细的策略
location /api {
content-security-policy "script-src 'strict-dynamic'; frame-ancestors 'none';";
}
# 更多规则可以按需添加
}
```
在这个例子中:
- `default-src 'self'` 指定了默认的源来自当前域名及其子域。
- `script-src`、`style-src` 和 `img-src` 分别定义了JavaScript、内联样式和图片的源。
- `frame-ancestors 'none'` 禁止页面嵌套在其他帧中。
请注意,每行的政策声明之间通常用分号(`;`)隔开,每个`policy`指令后面可能会跟一些选项来指定具体的行为。
nginx 添加 Content-Security-Policy 写法
在 Nginx 中添加 `Content-Security-Policy` (CSP) 是为了增强网站的安全性,通过限制客户端能访问的内容来源。CSP 允许开发者声明哪些资源(如脚本、样式表、图片等)可以从何处加载。基本的配置语法通常包含在 HTTP响应头的 `Content-Security-Policy` 字段中。例如,一个基础的CSP设置可能会像这样:
```nginx
server {
listen 80;
server_name yourdomain.com;
# 设置 CSP 规则
add_header Content-Security-Policy "default-src 'self'; script-src 'nonce-YOUR_TOKEN_HERE'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font- `default-src`: 定义默认内容源,`'self'` 表示只允许来自当前域内的资源。
- `script-src`: 指定JavaScript脚本的来源,这里设置了 `nonce-YOUR_TOKEN_HERE`,这是一个随机生成的值,用于防止跨站脚本攻击(XSS),每次请求都会改变,服务器端验证这个值才能执行。
- `style-src`: 类似于 `script-src`,但这里是处理内联样式。
- `img-src`: 定义图片来源,除了 `self` 和 `data:` 协议外,不允许其他外部图片。
- `font-src`: 设置字体来源。
- `object-src`: 控制嵌入式对象(如Flash)的加载。
阅读全文
相关推荐
















