gpt4 book ai didi

nginx 配置以启用具有源匹配的 CORS

转载 作者:行者123 更新时间:2023-12-03 16:45:10 28 4
gpt4 key购买 nike

我试过使用 a very popular config对于 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;
}
}
}

但是,此配置必须使用两个条件:一个是匹配原始域名,另一个是捕获预检请求。因此,当第二个条件匹配时,第一个条件的 header 不会添加到响应中。

根据 If Is Evil官方文章,这是 nginx 的预期行为。

If Is Evil那么如何在 nginx 中启用 CORS?或者也许有办法以某种方式克服这种限制?

最佳答案

您可以尝试使用 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 时才会添加它们。请求中存在 header 并匹配此正则表达式。

关于nginx 配置以启用具有源匹配的 CORS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54313216/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com