chaihongjun.me

nginx配置CORS(跨域)跨源资源共享

为了网站速度方面的优化,先后上了serviceworker和google的quicklink。两者都有通过浏览器新的API,fetch能力去提高页面速度。Fetch是准备替代XHR而生。但是无论是使用XHR还是fetch都有面对一个跨域的问题。这里有一份针对nginx后端做cors配置的清单:

set $cors '';    
if ($http_origin ~ '^https?://(localhost|www.yourdomain.com|www.yourotherdomain.com)') {    
set $cors 'true';    
}    
if ($cors = 'true') {    
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;    
}    
if ($request_method = 'OPTIONS') {    
# 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;    
}

将上面的代码可单独配置为一个配置文件,然后引入主机配置文件内。另外yourdomain改为你的域名。

另外,也可以直接在主机配置文件中加入下面这段代码:

location / {
     if ($request_method = 'OPTIONS') {
        add_header 'Access-Control-Allow-Origin' '*';
        add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
        #
        # Custom headers and headers various browsers *should* be OK with but aren't
        #
        add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
        #
        # 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;
     }
     if ($request_method = 'POST') {
        add_header 'Access-Control-Allow-Origin' '*';
        add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
        add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
        add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range';
     }
     if ($request_method = 'GET') {
        add_header 'Access-Control-Allow-Origin' '*';
        add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
        add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
        add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range';
     }
}

这样就解决了CORS。来源:https://enable-cors.org/server_nginx.html

知识共享许可协议本作品采用知识共享署名-非商业性使用-禁止演绎 4.0 国际许可协议进行许可。作者:柴宏俊»