【问题标题】:nginx returning index.html for js with 304 responsenginx 为带有 304 响应的 js 返回 index.html
【发布时间】:2022-02-11 15:12:43
【问题描述】:

我有一个 nginx 服务器,它在我的浏览器中显示 200 响应请求,例如

https://server.com/app/static/js/2.8cc049f3.chunk.js

并在服务器日志上显示 304

"GET /static/js/2.8cc049f3.chunk.js HTTP/1.1" 304 0 "https://server.com/app"

server.com 上运行的 nginx 前面还有另一个 nginx,它正在从路径中删除 app。根据server.com 上的 nginx 日志,它工作正常。 static 文件夹位于我的根目录 /usr/share/nginx/html/

我的浏览器接收到的js 文件的内容是index.html。但是,当我登录到服务器并运行时

curl http://localhost/static/js/2.8cc049f3.chunk.js

我得到了正确的 js 内容作为响应,并且在服务器打印的日志中 200

"GET /static/js/2.8cc049f3.chunk.js HTTP/1.1" 200 1570391 "-" "curl/7.80.0" "-"

这是我的nginx.conf

server {
    listen  80;
    root    /usr/share/nginx/html/;
    index   index.html;

    add_header X-Frame-Options "SAMEORIGIN";
    add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;

    location / {
        try_files $uri $uri/ /index.html;
    }

    location ~ ^/(static)/  {
        gzip_static on;
        gzip_types
            text/plain
            text/xml
            text/css
            text/comma-separated-values
            text/javascript application/x-javascript
            application/atom+xml;
        expires max;
    }
}

我读到 304 表示文件没有更改,并告诉您的浏览器使用其本地缓存,因此我清除了浏览器缓存。我还重新启动了 nginx,以为第一个请求会在服务器上给出 200 响应,但它仍然是 304。

基于本地 curl 请求成功,我认为我的 nginx.conf 没有任何问题。我不知道nginx是否以某种方式将index.html缓存为我的js的内容,或者我没有正确清除浏览器缓存。

我也很困惑,为什么服务器上的响应代码是 304,而我的浏览器中的响应代码是 200。

【问题讨论】:

  • 这与您的问题无关,但是您为什么使用正则表达式location ~ ^/(static)/ { ... } 而不是前缀location /static/ { ... }?由于功能相同,第二个性能更高。

标签: google-chrome nginx reverse-proxy


【解决方案1】:

HTTP 304 表示“未修改”。这是因为你在我们所说的 NGINX 服务器前面使用了另一个 NGINX 代理服务器。

第一个 NGINX 正在请求第二个 NGINX 的资源,而这个回答“嘿,自从您上次询问以来,该文件没有被修改”。

在这种情况下,检查第一个 NGINX 代理实例的配置或轮到您在第一个和 proxy_cache off; 中的缓存并检查结果会非常有帮助。

【讨论】:

    猜你喜欢
    • 2016-07-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-09
    • 2019-05-01
    • 1970-01-01
    • 2016-06-05
    相关资源
    最近更新 更多