Nginx

多個 CORS 來源。我應該使用 if 語句嗎?- NginX

  • June 5, 2019

我已經設置了一個 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';
   }

http://localhost:3000是用於測試目的。我目前正在嘗試實現相同的邏輯,但只允許 3 個特定的預定義域。我找到了一個可能的解決方案,建議我使用以下程式碼片段:

if ($http_origin ~* "^https?://example\.domain\.com$" ) {
   add_header Access-Control-Allow-Origin $http_origin;
}

我猜因為 NginX 不支持 if-elif-else 語法,所以我可以通過使用 3 個 if 語句來擺脫它。但是,我知道if 是邪惡的,如果不考慮某些事情,我可能會出現意想不到的行為。

我對 NginX 比較陌生,所以我的問題是,3-if 方法是否安全可靠?

通常,在您考慮使用ifnginx 的地方,使用它會更好map

在這種情況下,您將創建一個map說明所有允許的來源:

map $http_origin $origin_allowed {
  default 0;
  https://foo.example.com 1;
  https://bar.example.com 1;
  # ... add more allowed origins here
}

請注意,沒有嵌套if的 s。所以這行不通:

if ($request_method = 'OPTIONS') {
   if ($origin_allowed = 1) { 
        ...

進一步使用並考慮到如果值為空則不會發送任何內容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; 
  ...

特殊$origin變數將包含我們允許的來源之一,或者如果不匹配,則為空。使用add_header空值呼叫時,不會發送標頭。因此,它將僅針對允許的來源發送。

引用自:https://serverfault.com/questions/955255