Nginx

nginx:多個匹配的位置塊

  • June 13, 2017

我嘗試設置 max-age 標頭指令和 Content-Disposition “附件”,如下所示:

location / {

   # set up max-age header directive for certain file types for proper caching
   location ~* \.(?:css|js|ico|gif|jpe?g|png|mp3|mpeg|wav|x-ms-wmv|eot|svg|ttf|woff|woff2)$ {
       expires 7d;
       add_header Cache-Control "public";
   }

   # force download for ceratain file types
   location ~* \.(?:fb2|mobi|mp3)$ {
        add_header Content-Disposition "attachment";
   }
...
}

問題在於兩個位置塊都匹配的 .mp3 文件。僅使用第一個(max-age)。我怎樣才能同時擁有 .mp3 - max-ageContent-Disposition “附件”?

這裡有一篇關於伺服器和位置塊匹配的好文章。只有一個位置塊可以匹配,因此您將為 mp3 文件創建一個位置塊。

location ~*  \.mp3$ {
  expires 7d;
  add_header Cache-Control "public";
  add_header Content-Disposition "attachment";
}

Nginx 將匹配具有相同前綴的第一個位置塊,因此這需要放在兩個現有塊之前,或者您需要從其他兩個塊的匹配條件中刪除 mp3。

鑑於只使用了第一個位置,為什麼不這樣做呢?:

location / {

   # set up max-age header directive for certain file types for proper caching
   location ~* \.(?:css|js|ico|gif|jpe?g|png|mpeg|wav|x-ms-wmv|eot|svg|ttf|woff|woff2)$ {
       expires 7d;
       add_header Cache-Control "public";
   }

   # force download for ceratain file types
   location ~* \.(?:fb2|mobi)$ {
        add_header Content-Disposition "attachment";
   }

   # For mp3 files set both:
   location ~* \.mp3$ {
       expires 7d;
       add_header Cache-Control "public";
       add_header Content-Disposition "attachment";
   }

...
}

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