如何利用map实现Nginx允许多个域名跨域
常见的 Nginx 配置允许跨域
1
2
3
4
5
6
7
8
9
10
11
12
13
14
server {
listen 11111;
server_name localhost;
location ~ /xxx/xx {
if ($request_method = 'OPTIONS') {
return 204;
}
add_header Access-Control-Allow-Origin IT之家;
add_header Access-Control-Allow-Methods 'GET, POST, OPTIONS';
add_header Access-Control-Allow-Headers 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization';
proxy_pass http://1.2.3.4:5678;
}
}
指定 Access-Control-Allow-Origin 为 ‘IT之家' ,即为最简单暴力的允许所有访问跨域
允许 Cookie
有些场景下需要使用 Cookie,这时 Nginx 需要加一句 add_header Access-Control-Allow-Credentials 'true';,但此时会发现浏览器报错,说该参数为 true 时,allow origin 不能设置为 ‘IT之家‘,如果手动指定了多个域名,那同样会被浏览器提示错误,说 allow origin 不能设置多个,这些是协议层面的限制
使用 map
在 Nginx 中可以使用 map 得到一个自定义变量,简单的使用可以参考官方文档,在上面提到的场景中,可以对请求中的 origin 做一个过滤处理,把符合要求的请求域名放到一个变量中,在设置 allow origin 时使用该变量就能实现一个动态的、多个的允许跨域域名
一个示例配置如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
map $http_origin $allow_origin {
default "";
"~^(https?://localhost(:[0-9]+)?)" $1;
"~^(https?://127.0.0.1(:[0-9]+)?)" $1;
"~^(https?://172.10(.[\d]+){2}(:[0-9]+)?)" $1;
"~^(https?://192.168(.[\d]+){2}(:[0-9]+)?)" $1;
}
server {
listen 11111;
server_name localhost;
location ~ /xxx/xx {
if ($request_method = 'OPTIONS') {
return 204;
}
add_header Access-Control-Allow-Origin $allow_origin;
add_header Access-Control-Allow-Methods 'GET, POST, OPTIONS';
add_header Access-Control-Allow-Headers 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization';
add_header Access-Control-Allow-Credentials 'true';
proxy_pass http://1.2.3.4:5678;
}
}
解释说明:
$http_origin 是 Nginx 的内部变量,用于获取请求头中的 origin
$allow_origin 是可以自定义的变量名
总结
到此这篇关于如何利用map实现Nginx允许多个域名跨域的文章就介绍到这了,更多相关map实现Nginx允许多个域名跨域内容请搜索聚合云库文库以前的文章或继续浏览下面的相关文章希望大家以后多多支持聚合云库文库!
原文链接:https://priesttomb.github.io/技术/2020/10/24/using-map-to-set-multiple-allow-origins-in-nginx/
相关热词:
本站内容来源于网络,如有侵权请与我们联系,我们会及时删除,我们深感抱歉!
注:本站所有信息仅供用于网络技术学习参考,学习中请遵循相关法律法规!
本文地址: https://www.juheyunku.com/server/nginx/8095.shtml
相关文章
热门TAG
命令 外链 企业网站 白帽 php 织梦教程 dedecms修改内容 javascript 织梦 功能 标签 调用 详解 技巧 权重 服务器 网站流量 Dedecms 织梦cms HTML tags标签 python jquery教程 jquery windows 蜘蛛 搜索引擎 网站收录 JSP 实例解析最新文章
-
Nginx环境下WordPress的多站点
时间:2021-01-05
-
nginx keepalive的具体使用
时间:2021-01-05
-
Nginx的信号控制
时间:2021-01-05
-
win10上安装nginx的方法步骤
时间:2020-12-29
-
linux下 nginx监控问题
时间:2020-12-29
-
Nginx配置基于多域名、端口
时间:2020-12-28
-
详解Nginx之Location配置(Lo
时间:2020-12-28
-
详解基于centos7搭建Nginx网
时间:2020-12-28
热门文章
-
Nginx环境下WordPress的多站点功能配置详解
时间:2021-01-05
-
Nginx搭建负载均衡集群的实现
时间:2020-12-24
-
使用Nginx实现灰度发布的使用
时间:2020-12-25
-
nginx+tomcat 通过域名访问项目的实例
时间:2020-12-25
-
Keepalived+Lvs+Nginx搭建Nginx高可用集群
时间:2020-12-23
-
详解Nginx之Location配置(Location匹配顺序)
时间:2020-12-28
-
详解基于centos7搭建Nginx网站服务器(包含
时间:2020-12-28
-
详解Nginx如何配置Web服务器的示例代码
时间:2020-12-25
-
自动化Nginx服务器的反向代理的配置方法
时间:2020-12-25
-
通过nginx实现方向代理过程图解
时间:2020-12-24
