【问题标题】:nginx - Serve file conditionally without redirectionnginx - 有条件地提供文件而不重定向
【发布时间】:2012-12-13 17:54:15
【问题描述】:

我目前正在 Rails 中构建多域 cms。由于此内容在下一次更改之前是相同的,因此我想通过静态文件进行缓存。

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

public/
   assets/
      cms.css
   sites/
      foo.com/
         assets/
            screen-some-hash.min.css
         index.html
         asdf/
            index.html
      baz.com/
         assets/
            screen-some-hash.min.css
         index.html
         asdf/
            index.html

我想做的是:

将 www 重定向到非 www(有效)

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

对于所有其他请求(意味着没有子域): 如果路径包含 /assets 在 public/sites/$host$request_uri 中提供文件并将过期内容设置为 30d 左右。其他一切:检查 public/sites/$host$request_uri 或回退到 rails 应用程序。

除了 www/non-www 重定向之外,我从未使用过 nginx 条件,并且真的不知道我必须为上述条件做什么。如果可能的话,我不想对缓存的内容使用重定向(即重定向到/sites/foo.com/asdf),而是希望在转到http://foo.com/asdf 时让nginx 直接提供此文件。

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

【问题讨论】:

    标签: nginx passenger


    【解决方案1】:

    得到了一些有用的东西,不是 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;
      }
    }
    

    【讨论】:

      【解决方案2】:

      对于子域,这应该可以解决问题:

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

      不太确定 proxy_pass 设置,因为我使用 Ruby 应用程序的唯一经验是 Gitlab,我正在以这种方式运行它。我希望这至少有一点帮助。

      server {
          server_name example.com;
      
          location /assets {
              root /public/sites/$hostname/$request_uri;
              expires max;
          }
      }
      

      您必须添加自己的设置并稍微尝试一下,因为我现在没有机会实际测试它。但它应该会为您指明方向。

      【讨论】:

        猜你喜欢
        • 2017-04-07
        • 1970-01-01
        • 2018-08-04
        • 1970-01-01
        • 1970-01-01
        • 2016-02-12
        • 2021-01-30
        • 1970-01-01
        • 2023-04-09
        相关资源
        最近更新 更多