1、CORS
CORS是一个W3C的标准,全称是跨域资源共享(Cross-Origin Resource Sharing)。跨源资源共享是一种浏览器机制,可以控制对位于给定域之外的资源的访问。它扩展并增加了同源策略 ( SOP ) 的灵活性。但是,如果网站的 CORS 策略配置和实施不当,它也可能导致跨域攻击。CORS 不能防止跨域攻击,例如跨站点请求伪造( CSRF )。
跨域主要使用的4个响应头:
- Access-Control-Allow-Methods: 设置跨域允许的请求方法
- Access-Control-Allow-Headers: 设置跨域允许的自定义字段
- Access-Control-Allow-Credentials:设置跨域是否允许使用Cookies
- Access-Control-Allow-Origin: 设置跨域允许请求源地址,* 表示服务器可以接受所有来源的请求
2、解决
nginx配置跨域,对所有来源域名放行
server {
listen 80;
server_name localhost;
#*星号代表任意跨源请求都支持
add_header Access-Control-Allow-Origin '*';
add_header Access-Control-Allow-Methods 'GET, POST';
add_header Access-Control-Allow-Headers 'Cache-Control no-cache,no-store,must-revalidate';
}
Access-Control-Allow-Origin 配置为 * 的时候,因为允许所有的来源请求,所有这样是很不安全的,也不推荐这样使用
所有上面的跨域可以修改为对特定的域名放行
server {
listen 80;
server_name localhost;
#*星号代表任意跨源请求都支持
add_header Access-Control-Allow-Origin 'www.bgxwz.com';
add_header Access-Control-Allow-Methods 'GET, POST';
add_header Access-Control-Allow-Headers 'Cache-Control no-cache,no-store,must-revalidate';
}
Access-Control-Allow-Origin 配置为特定域名的话,目前是只支持单域名的,无法配置多个域名,即使配置了多个域名,也只会最后一个域名生效,那么这样肯定是无法满足企业需求的,对于多域名的跨域需求肯定是有的,所以就有了下面的多域名跨域支持
多域名跨域支持
# 后面有需要添加的新域名,直接往后面添加即可
map $http_origin $cors_origin {
default 0;
"~https://www.bgxwz.com" https://www.bgxwz.com;
"~https://blog.bgxwz.com" https://blog.bgxwz.com;
}
server {
listen 80;
server_name localhost;
add_header Access-Control-Allow-Origin $cors_origin;
add_header Access-Control-Allow-Credentials true;
add_header Access-Control-Allow-Methods "GET, POST, PUT, OPTIONS";
if ($request_filename ~* ^.*?.(html|css)$){
add_header Cache-Control no-cache,no-store,must-revalidate;
}
try_files $uri $uri/ /index.html;
index index.html index.htm;
}
评论区