nginx缓存未命中行为

时间:2012-11-12 14:49:40

标签: ruby-on-rails caching nginx

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

production.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;
  }

1 个答案:

答案 0 :(得分: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
}

这将尝试请求的网址,如果没有找到,请尝试替代uri(您还可以添加第3个,第4个,...选项)

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

有关try_files

的更多详细信息和一些示例,请参阅http://nginx.org/en/docs/http/ngx_http_core_module.html#try_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 "";
}

换言之,对于所有部分以/assets/开头的网址:

  1. 检查是否存在与路径对应的实际文件(即$uri指令的try_files部分)
  2. 如果没有,请将请求传递到指定位置@cache(这是@cache指令的try_files部分)
  3. 如果我们到达@cache位置,它将首先检查代理缓存区one是否匹配
  4. 如果未找到缓存匹配,则会将请求反向代理到http://127.0.0.1:81
  5. 上的rails应用
相关问题