nginx-无重定向有条件地服务文件

nginx-无重定向有条件地服务文件,nginx,passenger,Nginx,Passenger,我目前正在rails中构建一个多域cms。因为这个内容在下一次更改之前是相同的,所以我想通过静态文件进行缓存 包含foo.com和baz.com的一些缓存页面的公共目录(/和/asdf在这两种情况下): 我想做的是: 将www重定向到非www(works) 如果请求包含子域(cms、admin等): 如果路径包含/assets,则在public/assets中为文件提供服务,并将expire stuff设置为30d左右。这里没有问题,因为/assets=public/assets和public/

我目前正在rails中构建一个多域cms。因为这个内容在下一次更改之前是相同的,所以我想通过静态文件进行缓存

包含foo.com和baz.com的一些缓存页面的公共目录(/和/asdf在这两种情况下):

我想做的是:

将www重定向到非www(works)

如果请求包含子域(cms、admin等): 如果路径包含/assets,则在public/assets中为文件提供服务,并将expire stuff设置为30d左右。这里没有问题,因为/assets=public/assets和public/是乘客根目录。 其他一切:通过rails处理,无需特殊缓存或其他任何要求

对于所有其他请求(表示无子域): 如果路径包含/assets,则在public/sites/$host$request_uri中为文件提供服务,并将expire stuff设置为30d左右。其他一切:检查public/sites/$host$request\u uri或返回rails应用程序

除了www/non-www重定向之外,我从来没有使用过nginx条件,也不知道对于上面提到的条件我必须做什么。如果可能的话,我不想对缓存的东西使用重定向(即重定向到/sites/foo.com/asdf),而是希望nginx在访问时直接为这个文件提供服务


进一步:我不想硬编码主机名,因为我想处理未知数量的域。我也不想为此使用多个rails应用程序。

对于子域,这应该可以做到:

server {
    server_name ~^(?<subdomain>.+)\.example\.com$;
    access_log /var/log/nginx/$subdomain/access.log;
    location /assets {
        expires max;
    }
    location / {
        proxy_pass http://your_rails_app;
    }
}

你必须添加你自己的设置,玩一点,因为我现在没有机会真正测试它。但是它应该给你指明方向。

得到了一些有用的东西,不是100%,但现在已经足够好了

server {
  listen   80;
  server_name  *IP*;

  if ($host ~* www\.(.*)) {
    set $host_without_www $1;
    rewrite ^(.*)$ http://$host_without_www$1 permanent;
  }

  location ~ ^/(assets)/  {
    try_files /sites/$host$uri $uri @passenger;

    root /home/cms/app/current/public;
    gzip_static on;
    expires max;
    add_header Cache-Control public;
  }

  location / {
    try_files /sites/$host$uri/index.html /sites/$host$uri $uri @passenger;
    root   /home/cms/app/current/public;
  }

  location @passenger {
   access_log  /home/cms/app/shared/log/access.log;
   error_log  /home/cms/app/shared/log/error.log;
   root   /home/cms/app/current/public;
   passenger_enabled on;
  }
}
server {
    server_name example.com;

    location /assets {
        root /public/sites/$hostname/$request_uri;
        expires max;
    }
}
server {
  listen   80;
  server_name  *IP*;

  if ($host ~* www\.(.*)) {
    set $host_without_www $1;
    rewrite ^(.*)$ http://$host_without_www$1 permanent;
  }

  location ~ ^/(assets)/  {
    try_files /sites/$host$uri $uri @passenger;

    root /home/cms/app/current/public;
    gzip_static on;
    expires max;
    add_header Cache-Control public;
  }

  location / {
    try_files /sites/$host$uri/index.html /sites/$host$uri $uri @passenger;
    root   /home/cms/app/current/public;
  }

  location @passenger {
   access_log  /home/cms/app/shared/log/access.log;
   error_log  /home/cms/app/shared/log/error.log;
   root   /home/cms/app/current/public;
   passenger_enabled on;
  }
}