Last active
August 15, 2018 17:34
-
-
Save uicosp/7fbf25e6e64e7dfd7e3d3022fcfac439 to your computer and use it in GitHub Desktop.
最正确的 nginx 跨域配置
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 跨域规范请查阅 | |
# https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Access_control_CORS | |
set $cors 'FALSE'; | |
if ($http_origin ~ '^https?://(localhost|.*\.domain\.com)$') { | |
set $cors 'TRUE'; | |
} | |
if ($request_method = 'OPTIONS') { | |
set $flag "${cors}+PREFLIGHT"; | |
} | |
if ($request_method != 'OPTIONS') { | |
set $flag "${cors}+SIMPLE"; | |
} | |
# 简单请求 | |
if ($flag = 'TRUE+SIMPLE') { | |
add_header 'Access-Control-Allow-Origin' "$http_origin" always; | |
add_header 'Access-Control-Allow-Credentials' 'true' always; | |
# required to be able to read Authorization header in frontend | |
#add_header 'Access-Control-Expose-Headers' 'Authorization' always; | |
} | |
# 预检请求 | |
if ($flag = 'TRUE+PREFLIGHT') { | |
add_header 'Access-Control-Allow-Origin' "$http_origin" always; | |
add_header 'Access-Control-Allow-Credentials' 'true' always; | |
add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, DELETE, OPTIONS' always; | |
add_header 'Access-Control-Allow-Headers' 'Accept,Authorization,Cache-Control,Content-Type,DNT,If-Modified-Since,Keep-Alive,Origin,User-Agent,X-Requested-With' always; | |
# required to be able to read Authorization header in frontend | |
#add_header 'Access-Control-Expose-Headers' 'Authorization' always; | |
# | |
# Tell client that this pre-flight info is valid for 20 days | |
# | |
add_header 'Access-Control-Max-Age' 1728000; | |
add_header 'Content-Type' 'text/plain charset=UTF-8'; | |
add_header 'Content-Length' 0; | |
return 204; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment