【问题标题】:Using try_files alongside rewrite in nginx location block在 nginx 位置块中使用 try_files 和重写
【发布时间】:2016-10-26 22:59:38
【问题描述】:

我已经在 nginx 中大量使用 rewrite 来执行这种事情:

/photos/123344               ->    /photos/photos.php?id=123344
/photos/london-2016          ->    /photos/photo-shoot.php?name=london-2016

目前我对其他(非动态)页面没有规则。例如

/photos/shoot-register.php   ->    /photos/shoot-register.php

我想成为什么样的人

/photos/shoot-register.php   ->    /photos/shoot-register

但没有为每个 .php 文件指定单独的 rewrite 规则。

看来try_files 是正确的指令:

location ~ ^/photos {
    try_files $uri $uri.php?$args;
    rewrite ^/photos/([0-9]+)(/?)$        /photos/photo.php?id=$1;
    rewrite ^/photos/([^/\.]+)(/?)$       /photos/photo-shoot.php?name=$1;
}

但这不起作用,除非我删除两个重写行。

我认为这意味着在尝试文件后执行不会停止?它找到“shoot-register.php”,然后继续执行并以/photos/photo-shoot.php?name=shoot-register.php结束?

try_files 成功找到匹配后如何让它停止?

谢谢

【问题讨论】:

    标签: nginx url-rewriting


    【解决方案1】:

    如果您将重写移动到单独的命名位置,然后更改您的 try_file 指令以尝试文件,然后是 php 文件,然后指向新位置?

    location ~ ^/photos {
        try_files $uri $uri.php?$args @rewrites;
    }
    
    location @rewrites {
        rewrite ^/photos/([0-9]+)(/?)$        /photos/photo.php?id=$1;
        rewrite ^/photos/([^/\.]+)(/?)$       /photos/photo-shoot.php?name=$1;
    }
    

    【讨论】:

    • 当然是一个可行的解决方案,这是最佳实践吗,与未经训练的眼睛相比似乎没有必要?
    • 这是我唯一能想到的。问题是当其中一个选项有效时,try_files 指令不会停止并返回。在您的版本中,它将在 .php 部分停止,然后继续执行 location 指令。在我的版本中,它做同样的事情,但由于不存在重写指令,它会返回您期望的内容。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-27
    • 2013-11-29
    • 1970-01-01
    相关资源
    最近更新 更多