1

当给定路径不存在时,是否可以告诉 nginx 另一个位置?我想从我的 Rails 应用程序中提供静态资产,但是有时编译的资产可能不可用,我想有一个后备。

生产.rb

  # Disable Rails's static asset server (Apache or nginx will already do this)
  config.serve_static_assets = false

nginx.conf:

  location ~ ^/assets/ {
               expires max;
               add_header Cache-Control public;
               add_header ETag "";
               break;
  }

更新: nginx.conf

  #cache server
  server {
        listen 80;

        # serving compressed assets
        location ~ ^/(assets)/  {
                root /var/app/current/public;
                gzip_static on; # to serve pre-gzipped version
                expires max;
                add_header Cache-Control public;
                add_header ETag "";
        }

        try_files $uri /maintenance.html @cache;

        location @cache {
            proxy_redirect off;
            proxy_pass_header Cookie;
            proxy_ignore_headers Set-Cookie;
            proxy_hide_header Set-Cookie;
            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_cache one;
            proxy_cache_key app$request_uri;
            proxy_cache_valid 200 302  5s;
            proxy_cache_valid 404      1m;
            proxy_pass http://127.0.0.1:81;
        }
  }

  #real rails backend
  server {
        listen 81;
        root /var/app/current/public;
        error_log /var/app/current/log/error.log;

        rails_env production;
        passenger_enabled on;
        passenger_use_global_queue on;
  }
4

1 回答 1

1

是的,使用 try files 指令:

# note: you don't need the overhead of regexes for this location
location /assets/ {
   try_files $uri /alternative_to_try
   # ... add back in rest of your assetts config
}

这将尝试请求的 url,如果找不到,请尝试替代 uri(您也可以添加第 3、4、... 选项)

请注意,/alternative uri 可以是命名位置(例如,用于将 url 传递给 rails 应用程序的指令)

有关更多详细信息和一些示例,请参见http://nginx.org/en/docs/http/ngx_http_core_module.html#try_filestry_files

更新:

对,所以将您的资产位置更改为

location /assets/  {
   try_files $uri @cache;
   root /var/app/current/public;
   gzip_static on; # to serve pre-gzipped version
   expires max;
   add_header Cache-Control public;
   add_header ETag "";
}

换句话说,对于所有以 url 开头的部分/assets/

  1. 检查是否有对应于路径的实际文件(这是指令的$uri一部分)try_files
  2. 如果不是,则将请求传递到命名位置 @cache(这是指令的@cache一部分)try_files
  3. 如果我们到达该@cache位置,它将首先检查代理缓存区域one是否匹配
  4. 如果没有找到缓存匹配,它会将请求反向代理到 rails 应用程序http://127.0.0.1:81
于 2012-11-12T15:06:34.930 回答