简体   繁体   English

如何将 NGINX 配置为仅服务器一个 static 文件?

[英]How to configure NGINX to server only one static file?

Our Rails application is running on puma/nginx below part of the NGINX configuration.我们的 Rails 应用程序在 NGINX 配置的一部分下方的 puma/nginx 上运行。

What's I'm trying to achieve is that when the request URL is http://example.com it will serve a static cached file from /public/cached_pages/index.html and in all other cases works like it is now so passing the request to rails/puma What's I'm trying to achieve is that when the request URL is http://example.com it will serve a static cached file from /public/cached_pages/index.html and in all other cases works like it is now so passing the请求 rails/puma

upstream rails {
  server unix:///var/www/html/cms/shared/sockets/puma.sock;
}


   location / {
       proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
       add_header Cache-Control "public";
       expires 2d;
       proxy_set_header Host $http_host;
       proxy_set_header  X-Forwarded-Proto $scheme;
       proxy_set_header  X-Forwarded-Ssl on; # Optional
       proxy_set_header  X-Forwarded-Port $server_port;
       proxy_pass http://rails;
  }

I am not sure if it is the best solution, but did you try try_files ?我不确定这是否是最好的解决方案,但是您尝试过try_files吗? ( Nginx docs ) In the rails context this is often used for assets, but might also work for your cache. ( Nginx docs ) 在 rails 上下文中,这通常用于资产,但也可能适用于您的缓存。 The asset example would be something like this:资产示例将是这样的:

  try_files $uri/index.html $uri @app_production;
  location @app_production {
[...]
    proxy_redirect off;
    proxy_pass http://app_production;

The first line would need to be adjusted to your needs, but this might also work for your case.第一行需要根据您的需要进行调整,但这也可能适用于您的情况。

You should use the location directive您应该使用location指令

  location = / {
    gzip_static on;
    root public/cached_pages
    index.html
  }

The = symbol will provide an exact match for the url, without the = symbol you will be matching any path whatsoever after the domain name. =符号将为 url 提供完全匹配,如果没有=符号,您将匹配域名之后的任何路径。 Next, switching gzip on will compress the file to reduce traffic bandwidth so that the index.html page will be zipped then setting the root directive to be the path to the file will enable nginx to find the file you want to serve, then the actual file itself should do the trick for you.接下来,打开 gzip 将压缩文件以减少流量带宽,因此 index.html 页面将被压缩,然后将root指令设置为文件的路径将使 nginx 找到您要服务的文件,然后实际文件本身应该为您解决问题。

The root directive may need the full path to the folder rather than the relative public path, Obviously I do not know what that will be. root 指令可能需要文件夹的完整路径而不是相对公共路径,显然我不知道那会是什么。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM