Nginx 中配置跨域

Nginx 中配置跨域

允许单域名跨域

如果只需要允许一个域名跨域,直接在 server 段中添加以下配置:

1
2
3
4
5
6
7
8
9
location / {
add_header Access-Control-Allow-Origin 'http://example.com';
add_header Access-Control-Allow-Credentials 'true';
add_header Access-Control-Allow-Methods 'PUT, POST, GET, DELETE, OPTIONS';
add_header Access-Control-Allow-Headers 'Content-Type, Authorization';
if ($request_method = 'OPTIONS') {
return 204;
}
}

允许单域名跨域

如果需要允许多域名跨域,可以先在 http 段中添加以下配置:

1
2
3
4
5
map $http_origin $cors_origin {
default 0;
"~http://example.com" http://example.com;
"~http://www.example.com" http://www.example.com;
}

然后在 server 段中添加以下配置:

1
2
3
4
5
6
7
8
9
location / {
add_header Access-Control-Allow-Origin $cors_origin;
add_header Access-Control-Allow-Credentials 'true';
add_header Access-Control-Allow-Methods 'PUT, POST, GET, DELETE, OPTIONS';
add_header Access-Control-Allow-Headers 'Content-Type, Authorization';
if ($request_method = 'OPTIONS') {
return 204;
}
}

最后重启 nginx 服务生效。