为什么NGinX没有重定向到我的缓存文件?

时间:2011-04-23 15:49:26

标签: ruby-on-rails-3 nginx

我有一个子应用程序的rails应用程序。

我已更改了应用中的默认缓存位置,以便将模板写入:

[APP_DIR] /公共/高速缓存/ [亚结构域] / [路径]

所以,请求:

http://france.mysite.com/recipes.html

将写信给:

[my_app]/public/cache/france/recipes.html

这工作正常,文件正被写入服务器上的正确位置。

我的问题是NGinx没有提供这些缓存文件。

我已将以下内容添加到我的NGinx配置中:

    # catch requests to www and remove the 'www'
    server {
      server_name www.mysite.com;
      rewrite ^ $scheme://mysite.com$request_uri permanent;
    }


    server {
      server_name mysite.com *.mysite.com;

      access_log /home/deploy/mysite/staging/current/log/access.log;
      error_log /home/deploy/mysite/staging/current/log/error.log;

      root   /home/deploy/mysite/staging/current/public;

      passenger_enabled on;
      rails_env staging;

      client_max_body_size 400M;
      client_body_buffer_size 128k;

        if (-f $request_filename) {
          break;
        }

        # Check / files with index.html
        if (-f $document_root/cache/$host/$uri/index.html) {
          rewrite (.*) /cache/$host/$1/index.html break;
        }

        # Check the path + .html
        if (-f $document_root/cache/$host/$uri.html) {
          rewrite (.*) /cache/$host/$1.html break;
        }

        # Check directly
        if (-f $document_root/cache/$host/$uri) {
          rewrite (.*) /cache/$host/$1 break;
        }


    }

有人可以指出我出错的地方吗? :/

1 个答案:

答案 0 :(得分:0)

所以我能够解决这个问题...

NGinx中的$ host变量指的是整个主机(我错误地认为它只是子域名:/)

两个解决方法:

a)更改缓存目录以匹配完整主机名:     http://france.mysite.com => /public/cache/france.mysite.com

b)从主机中获取子域,并在if块中使用它:

server {
  server_name www.mysite.com;
  rewrite ^ $scheme://mysite.com$request_uri permanent;
}


server {
  server_name mysite.com *.mysite.com;

  access_log /home/deploy/mysite/staging/current/log/access.log;
  error_log /home/deploy/mysite/staging/current/log/error.log;

  root   /home/deploy/mysite/staging/current/public;

  passenger_enabled on;
  rails_env staging;

  client_max_body_size 400M;
  client_body_buffer_size 128k;

  # if the maintenance file exists, redirect all requests to it
  if (-f $document_root/system/maintenance.html) {
    rewrite ^(.*)$ /system/maintenance.html break;
  }

  # if the host has a subdomain, set $subdomain
  if ($host ~* "(.*)\.mysite.com"){
    set $subdomain $1;
  }

  # Rewrite index.html.
  if (-f $document_root/cache/$subdomain/$uri/index.html) {
    rewrite ^(.*)$ /cache/$subdomain/$uri/index.html break;
  }

  # Rewrite other *.html requests.
  if (-f $document_root/cache/$subdomain/$uri.html) {
    rewrite ^(.*)$ /cache/$subdomain/$uri.html break;
  }

  # Rewrite everything else.
  if (-f $document_root/cache/$subdomain/$uri) {
    rewrite ^(.*)$ /cache/$subdomain/$uri break;
  }
}

我选择了b)因为我觉得它更整洁