【问题标题】:nginx location with no code being skipped over没有代码被跳过的 nginx 位置
【发布时间】:2015-08-27 07:48:55
【问题描述】:

我正在尝试让 nginx在特定文件集的响应中放置一些标头。一般来说,我们希望设置标题以避免缓存,但是在 IE 中存在一个 font-awesome 的错误,如果它设置为不缓存,它会中断。我们已决定避免缓存字体文件。

代码如下:

location /app-name {
  alias   /usr/local/nginx-sites/<app-folder>/current;

  location ~ /app-name/(.*\.(woff|ttf))$ {
    add_header X-FONT "$1"; # if I comment this out, then I get the headers below
  }

  add_header Cache-Control "no-cache, no-store, must-revalidate";
  add_header Pragma "no-cache";
  add_header Expires "0";

  index  index.html index.htm;
}

正如代码一样,它可以工作。但是,如果我注释掉 add_header X-FONT "$1";,它会返回为带有不需要的标头的文件提供服务。我宁愿不必传入随机标头,这样 nginx 就会做我期望的事情。好像有点没意思。

使用 X-FONT 标题:

> GET /<app-name>/fonts/fontawesome-webfont.woff?v=4.2.0 HTTP/1.1
> User-Agent: curl/7.22.0 (x86_64-pc-linux-gnu) libcurl/7.22.0 OpenSSL/1.0.1 zlib/1.2.3.4 libidn/1.23 librtmp/2.3
> Host: localhost
> Accept: */*
>
< HTTP/1.1 200 OK
< Server: nginx/1.1.19
< Date: Thu, 27 Aug 2015 07:50:17 GMT
< Content-Type: application/octet-stream
< Content-Length: 65452
< Last-Modified: Thu, 27 Aug 2015 01:56:10 GMT
< Connection: keep-alive
< X-FONT: fonts/fontawesome-webfont.92e68ff4.woff
< Accept-Ranges: bytes

没有 X-FONT 标题:

> GET /<app-name>/fonts/fontawesome-webfont.woff?v=4.2.0 HTTP/1.1
> User-Agent: curl/7.22.0 (x86_64-pc-linux-gnu) libcurl/7.22.0 OpenSSL/1.0.1 zlib/1.2.3.4 libidn/1.23 librtmp/2.3
> Host: localhost
> Accept: */*
>
< HTTP/1.1 200 OK
< Server: nginx/1.1.19
< Date: Thu, 27 Aug 2015 07:53:15 GMT
< Content-Type: application/octet-stream
< Content-Length: 65452
< Last-Modified: Thu, 27 Aug 2015 01:56:10 GMT
< Connection: keep-alive
< Cache-Control: no-cache, no-store, must-revalidate
< Pragma: no-cache
< Expires: 0
< Accept-Ranges: bytes

我们正在运行:nginx/1.1.19。我也试过:nginx/1.6.2 (Ubuntu) 在虚拟机中得到相同的结果。

有没有更好的方法来做到这一点?

【问题讨论】:

  • 不要使用嵌套位置
  • 或试试add_header x-font "";
  • 添加空标题就可以了。我不喜欢我在配置中有那个标题(我在技术上没有使用),但它比将它发送给客户端要好。谢谢!

标签: nginx configuration


【解决方案1】:

根据this answer to a similar question,您应该能够使用否定查找语法从正在发送的缓存标头中排除 woff 和 ttf 文件扩展名:

location ~ .+(?<!\.woff)$ {
    location ~ .+(?<!\.ttf)$ {
        add_header Cache-Control "no-cache, no-store, must-revalidate";
        add_header Pragma "no-cache";
        add_header Expires "0";
    }
}

【讨论】:

  • 我喜欢你的回答。但是当我尝试它时,我得到了pcre_compile() failed: lookbehind assertion is not fixed length in ".+(?&lt;!\.(woff|ttf))$" at ")$"
  • 感谢您的回复。我已更改我的帖子以使用嵌套条件。在我的 nginx 环境中,configtest 使用新的嵌套配置成功。
猜你喜欢
  • 2020-09-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-21
  • 1970-01-01
  • 1970-01-01
  • 2021-08-27
相关资源
最近更新 更多