我已经设置了一个 NginX,以便从实例中提供一些静态文件。
静态文件将由我拥有的 3 个不同域使用。
NginX 服务器位于其自己的(第 4 个)域中。我想限制对我的文件的访问并应用 CORS 策略。
我已经研究过如何实现这一点,并且我确实做到了。在我的位置块中,我测试了以下代码:
if ($request_method = 'OPTIONS') {
add_header 'Access-Control-Allow-Origin' 'http://localhost:3000';
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 = 'GET') {
add_header 'Access-Control-Allow-Origin' 'http://localhost:3000';
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';
}
Run Code Online (Sandbox Code Playgroud)
该http://localhost:3000
是用于测试目的。我目前正在尝试实现相同的逻辑,但只允许 3 个特定的预定义域。我找到了一个可能的解决方案,建议我使用以下代码片段:
if ($http_origin ~* "^https?://example\.domain\.com$" ) {
add_header Access-Control-Allow-Origin $http_origin;
}
Run Code Online (Sandbox Code Playgroud)
我猜因为 NginX 不支持 if-elif-else 语法,所以我可以通过使用 3 个 if 语句来摆脱它。但是,我知道if 是邪恶的,如果不考虑某些事情,我可能会出现意外行为。
我对 NginX 比较陌生,所以我的问题是,3-if 方法安全可靠吗?
通常,在您考虑if
与 nginx 一起使用的地方,最好使用它map
。
在这种情况下,您将创建一个map
声明所有允许的来源:
map $http_origin $origin_allowed {
default 0;
https://foo.example.com 1;
https://bar.example.com 1;
# ... add more allowed origins here
}
Run Code Online (Sandbox Code Playgroud)
请注意,没有嵌套的if
s。所以这行不通:
if ($request_method = 'OPTIONS') {
if ($origin_allowed = 1) {
...
Run Code Online (Sandbox Code Playgroud)
把map
进一步的使用和占这一事实add_header
不会发送任何东西,如果该值是空的,你可以有一些作品:
map $http_origin $origin_allowed {
default 0;
https://foo.example.com 1;
https://bar.example.com 1;
# ... add more allowed origins here
}
map $origin_allowed $origin {
default "";
1 $http_origin;
}
if ($request_method = 'OPTIONS') {
add_header 'Access-Control-Allow-Origin' $origin;
...
Run Code Online (Sandbox Code Playgroud)
特殊$origin
变量将包含我们允许的来源之一,或者如果不匹配,则为空。当add_header
以空值调用时,将不会发送标头。因此,它将仅针对允许的来源发送。