如何利用map实现Nginx允许多个域名跨域
常见的Nginx配置允许跨域
server{ listen11111; server_namelocalhost; location~/xxx/xx{ if($request_method='OPTIONS'){ return204; } add_headerAccess-Control-Allow-Origin*; add_headerAccess-Control-Allow-Methods'GET,POST,OPTIONS'; add_headerAccess-Control-Allow-Headers'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization'; proxy_passhttp://1.2.3.4:5678; } }
指定Access-Control-Allow-Origin为‘*',即为最简单暴力的允许所有访问跨域
允许Cookie
有些场景下需要使用Cookie,这时Nginx需要加一句add_headerAccess-Control-Allow-Credentials'true';,但此时会发现浏览器报错,说该参数为true时,alloworigin不能设置为‘*‘,如果手动指定了多个域名,那同样会被浏览器提示错误,说alloworigin不能设置多个,这些是协议层面的限制
使用map
在Nginx中可以使用map得到一个自定义变量,简单的使用可以参考官方文档,在上面提到的场景中,可以对请求中的origin做一个过滤处理,把符合要求的请求域名放到一个变量中,在设置alloworigin时使用该变量就能实现一个动态的、多个的允许跨域域名
一个示例配置如下:
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{ listen11111; server_namelocalhost; location~/xxx/xx{ if($request_method='OPTIONS'){ return204; } add_headerAccess-Control-Allow-Origin$allow_origin; add_headerAccess-Control-Allow-Methods'GET,POST,OPTIONS'; add_headerAccess-Control-Allow-Headers'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization'; add_headerAccess-Control-Allow-Credentials'true'; proxy_passhttp://1.2.3.4:5678; } }
解释说明:
$http_origin是Nginx的内部变量,用于获取请求头中的origin
$allow_origin是可以自定义的变量名
总结
到此这篇关于如何利用map实现Nginx允许多个域名跨域的文章就介绍到这了,更多相关map实现Nginx允许多个域名跨域内容请搜索毛票票以前的文章或继续浏览下面的相关文章希望大家以后多多支持毛票票!