5

nginx开启跨域CORS

 2 years ago
source link: https://garywu520.github.io/2022/02/08/nginx%E5%BC%80%E5%90%AF%E8%B7%A8%E5%9F%9FCORS/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

nginx开启跨域CORS

2022-02-08

字数统计: 268字

  |   阅读时长≈ 1分

跨域与同源策略简介

通常基于安全考虑,Nginx启用了同源策略,即限制了从同一个源加载的文档或脚本与来自另一个源的资源进行交互。这是一个用于隔离潜在恶意文件的重要安全机制。

而同源策略是一个安全策略。同源,指的是协议,域名,端口相同。浏览器处于安全方面的考虑,只允许本域名下的接口交互,不同源的客户端脚本,在没有明确授权的情况下,不能读写对方的资源。

Nginx多网站配置跨域

#配置多个域名在map中 只有配置过的才允许跨域
map $http_origin $corsHost {
"~https://mysite.io" https://mysite.io;
"~https://www.mysite.io" https://www.mysite.io;
}


server {
...
location / {
# 允许 所有头部 所有$corsHost域 所有方法
add_header 'Access-Control-Allow-Origin' $corsHost;
add_header 'Access-Control-Allow-Headers' '*';
add_header 'Access-Control-Allow-Methods' '*';
# OPTIONS 直接返回204
if ($request_method = 'OPTIONS') {
return 204;
}
}
...
}

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK