【问题标题】:How to configure nginx to try_files first, if not exists follow the request_uri如何先配置 nginx 到 try_files,如果不存在,请按照 request_uri
【发布时间】:2013-08-09 16:04:55
【问题描述】:

我们有带有 id 分区和子域的页面缓存。说ny.site.com/cat/12345la.site.com/dog/234之类的请求,nginx需要

  1. 检查文件/cat/ny/1234/5.html是否存在,返回
  2. 否则,就用原来的request_uri去打应用服务器,缓存文件就创建好了

我们设法找出了子域和 id 分区部分,但在 try_files 部分没有得到任何运气。总是得到无限循环错误,如rewrite or internal redirection cycle while internally redirecting to

我们的 nginx.conf 文件是这样的

rewrite "/cat/([0-9]{4})([0-9]{1,4})" /system/cache/cat/$subdomain/$1/$2.html break;
rewrite "/cat/([0-9]{1,4})" /system/cache/cat/$subdomain/$1.html break;
try_files $uri $request_uri;

有什么提示吗?谢谢!

更新: 我尝试了以下。 Nginx 在文件系统中寻找 $request_uri(例如 /cat/12345)而不是访问应用服务器。有什么想法吗?

try_files $uri @old;
location @old {
    rewrite ^ $request_uri break;
}

【问题讨论】:

    标签: nginx rewrite page-caching


    【解决方案1】:

    试试这个

    location ^~ ^/cat/([0-9]{4})([0-9]{1,4}) {
    
        try_files "/cat/ny/$1/$2.html" @app_server;
    
    }
    location @app_server{
    
        # pass this to your app server for processing.
    
    }
    
    1. 使用 ^~,因为这还将包括边缘情况,例如 /cat/12345/(结束斜线)。
    2. 只要确定你想要$uri(没有查询字符串)还是$request_uri (其中包含查询字符串)。

    【讨论】:

    • @surajs21:我有像 www.test.com/public/www.test.com/public/webwww.test.com/public/web1 这样的网址。这是 ZF2 我面临的问题是它可以正确获取到第一个 URL 'public/' 的链接,但问题是 www.test.com/public/webwww.test.com/public/web1。 ngin x 无法映射它。请帮助我stackoverflow.com/questions/21377321/…
    【解决方案2】:

    我自己之前从未尝试过,但我就是这样写的

    location / { # or whatever location you see fit to your requirements
        try_files $uri.html $uri;
        # I don't know if the `.` needs to be escaped `$uri\.html`, you can try both
    }
    

    【讨论】:

    • 感谢您的输入,但我不明白。这个 try_files 将如何解决问题?即,当磁盘上不存在 $uri 时,回到原来的 $request_uri?
    • try_files 告诉 nginx 为该请求尝试什么,所以我只是告诉它查看$uri 是否有一个 html 文件,否则尝试$uri,如果你有一个处理请求的 php 文件,然后你应该将它作为第三个参数传递,即:/index.php$request_uri 例如
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-25
    • 2013-09-23
    • 1970-01-01
    • 2019-12-24
    • 2013-05-17
    • 1970-01-01
    相关资源
    最近更新 更多