nginx:多个匹配的位置块

nginx:多个匹配的位置块

我尝试设置 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-age内容处置“附件”?

答案1

有一篇很好的文章此处匹配服务器和位置块。只有一个位置块可以匹配,因此您将创建一个仅针对 mp3 文件的位置块。

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

Nginx 将匹配具有相同前缀的第一个位置块,因此这需要放在两个现有块之前,或者您需要从其他两个块的匹配条件中删除 mp3。

答案2

鉴于仅使用第一个位置,为什么不这样做呢?:

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";
    }

...
}

相关内容