Nginx子域名跨域的广泛匹配设置方法
#Option 1 允许所有域名跨域
最简单直接的方法
Access-Control-Allow-Origin: *
#Option2 只允许域名及子域名
server { listen 80 default_server; server_name _; location / { # # NOTE: CORS standards allow a specific protocol/host combination, # 'null', or '*' only. So, wildcard subdomains won't work. # # Have a look here: # http://enable-cors.org/server_nginx.html # if ($http_origin ~* (https?://[^/]*\.your-domain.com(:[0-9]+)?)$) { add_header 'Access-Control-Allow-Origin' "${http_origin}"; } } } map $http_origin $allow_origin { ~^https?://(.*\.)?your-domain.com(:\d+)?$ $http_origin; ~^https?://(.*\.)?localhost(:\d+)?$ $http_origin; default ""; } server { listen 80 default_server; server_name _; add_header 'Access-Control-Allow-Origin' $allow_origin; # ... }
注意,除此以外还要注意服务端的应用的跨域设置,以NodeBB为例,在完成nginx以上的设置后还需要进入Settings
-> Advanced
设置 Access-Control-Allow-Origin
跨域参数。