支持CORS与来源匹配的Nginx配置 [英] nginx config to enable CORS with origin matching
本文介绍了支持CORS与来源匹配的Nginx配置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我尝试使用a very popular configfor nginx,它启用CORS并支持使用正则表达式进行来源匹配。
这是我的配置:
server {
listen 80 default_server;
root /var/www;
location / {
if ($http_origin ~ '^http://(www.)?example.com$') {
add_header Access-Control-Allow-Origin "$http_origin";
}
# Handling preflight requests
if ($request_method = OPTIONS) {
add_header Content-Type text/plain;
add_header Content-Length 0;
return 204;
}
}
}
但是,此配置必须使用两个条件:一个匹配原始域名,另一个捕获印前检查请求。因此,当第二个条件匹配时,第一个条件的标头不会添加到响应中。
根据If Is Evil官方文章,这是nginx的预期行为。
ifIf Is Evil
如何在nginx中启用CORS THEN?或者也许有办法以某种方式克服这一限制?
推荐答案
您可以尝试使用map
而不是第一个if
块:
map $http_origin $allow_origin {
~^http://(www.)?example.com$ $http_origin;
}
map $http_origin $allow_methods {
~^http://(www.)?example.com$ "OPTIONS, HEAD, GET";
}
server {
listen 80 default_server;
root /var/www;
location / {
add_header Access-Control-Allow-Origin $allow_origin;
add_header Access-Control-Allow-Methods $allow_methods;
# Handling preflight requests
if ($request_method = OPTIONS) {
add_header Content-Type text/plain;
add_header Content-Length 0;
return 204;
}
}
}
nginx将拒绝添加空的HTTP标头,因此仅当请求中存在Origin
标头并且与此正则表达式匹配时才会添加它们。
这篇关于支持CORS与来源匹配的Nginx配置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文