把下面的配置保存为 cors.conf 到 nginx 配置目录,通过 include 指令进行复用 ,在需要的 location 段引入该配置,如
location ~* ^/api/ {
include /usr/local/nginx/conf/cors.conf;
}
cors.conf 内容
#CORS
# #Allow all requset/method/header/custom credentials
add_header 'Access-Control-Allow-Origin' $http_origin always;
#add_header 'Access-Control-Allow-Origin' '*' always;
add_header 'Access-Control-Allow-Headers' $http_access_control_request_headers always;
add_header 'Access-Control-Allow-Credentials' 'true' always;
add_header 'Access-Control-Max-Age' 86400 always;
# 缓存 + 预检复用,动态允许所有方法可能会翻车,并且某些请求根本没有 Access-Control-Request-Method,Access-Control-Allow-Methods 的语义是:
# 服务器支持哪些方法,而不是 我允许你这一次用什么方法,所以最好明确定义
#add_header 'Access-Control-Allow-Methods' $http_access_control_request_method always;
# 把 http RFC 现行标准里的核心方法 + WebDAV 的 RFC 标准定义的方法全部允许
add_header 'Access-Control-Allow-Methods' 'GET,HEAD,POST,PUT,DELETE,TRACE,OPTIONS,PATCH,CONNECT,COPY,LOCK,MKCOL,MOVE,PROPPATCH,PROPFIND,UNLOCK,REPORT,CHECKOUT,MERGE,MKACTIVITY,SEARCH,ACL,LINK,UNLINK,PRI' always;
add_header Vary "Origin" always;
if ($request_method = 'OPTIONS') {
return 204 always;
}