nginx跨域设置防止cors漏洞
时间: 2023-12-10 18:33:55 浏览: 130
跨域资源共享 CORS 详解
为了防止CORS漏洞,可以在Nginx服务器上进行以下设置:
1. 在Nginx配置文件中添加以下内容:
```nginx
location / {
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Credentials' 'true';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
if ($request_method = 'OPTIONS') {
return 204;
}
}
```
2. 在Nginx配置文件中添加以下内容,以允许特定的域名进行跨域请求:
```nginx
location / {
if ($http_origin ~* (http://localhost:8080|http://www.example.com)) {
add_header 'Access-Control-Allow-Origin' "$http_origin";
add_header 'Access-Control-Allow-Credentials' 'true';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
}
if ($request_method = 'OPTIONS') {
return 204;
}
}
```
3. 在Nginx配置文件中添加以下内容,以允许所有域名进行跨域请求:
```nginx
location / {
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Credentials' 'true';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
if ($request_method = 'OPTIONS') {
return 204;
}
}
```
4. 在Nginx配置文件中添加以下内容,以允许特定的域名进行跨域请求,并且允许特定的HTTP方法:
```nginx
location / {
if ($http_origin ~* (http://localhost:8080|http://www.example.com)) {
add_header 'Access-Control-Allow-Origin' "$http_origin";
add_header 'Access-Control-Allow-Credentials' 'true';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
}
if ($request_method = 'OPTIONS') {
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
return 204;
}
}
```
阅读全文