强制 nginx 到 return 404 丢失资产

Force nginx to return 404 for missing assets

我们在 Rails 应用程序中使用 Nginx。我们在 Rails 日志文件中看到请求寻找不再存在的资产,如下所示:

Aug  8 09:18:06 www rails-prod ActionController::RoutingError (No route matches [GET] 
"/assets/application-cd8df963daec0c7c81c70254f7549eb028980b5a39df2c2c16fd4e6f9794c4b4.css"):

每次我们更改 css 时,url 中的哈希都会更改,因此该资产不再存在是正确的。

Rails 服务器不响应资产请求,因为所有资产都是预编译的。我们如何强制 Nginx 出现 return 404 错误?

这是 Nginx 配置文件:

upstream my_app {
  server unix:///var/run/puma/my_app.sock;
}

server {
  listen 80;
  server_name _ localhost; # need to listen to localhost for worker tier

  location / {
    proxy_pass http://my_app; # match the name of upstream directive which is defined above
    proxy_set_header Host $host;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
  }

  location /assets {
    alias /var/app/current/public/assets;
    gzip_static on;
    gzip on;
    expires max;
    add_header Cache-Control public;
  }

  location /public {
    alias /var/app/current/public;
    gzip_static on;
    gzip on;
    expires max;
    add_header Cache-Control public;
  }
}

试图将 break; 添加到 location /assets 组,但没有帮助。还尝试将 alias 更改为 root,但这也没有用。

您尝试过使用 try_files 吗?它会像这样(您可以找到并使用它的其他用法来解决您的特定问题):

  location /assets {
    try_files $uri @missing
  }

  location @missing {
    return 404;
  }

Nginx 将尝试处理请求,但如果发现文件丢失,它将 return 404。