【问题标题】:Nginx rewrite with and without trailing slashNginx 重写带和不带斜杠
【发布时间】:2017-06-15 20:57:19
【问题描述】:

我正在尝试创建一组规则来匹配带有和不带有斜杠的 url

大多数答案都指向我使用类似的东西。

location /node/file/ {                                                                                         
    rewrite ^/node/file/(.*)/(.*)$ /php/node-file.php?file=$1&name=$2;                                    
    rewrite ^/node/file/(.*)/(.*)/?$ /php/node-file.php?file=$1&name=$2;                                   │
}   

但这与结尾的斜杠 url 不匹配。

我如何编写一个匹配看起来像这样的 url 的规则

http://example.com/node/file/abcd/1234/
http://example.com/node/file/abcd/1234

【问题讨论】:

    标签: nginx nginx-location


    【解决方案1】:

    第一个rewrite 语句包含(.*) 作为最后一个捕获,它将匹配任何字符串,包括带有斜杠的字符串。

    使用字符类[^/] 匹配除/ 之外的任何字符:

    rewrite ^/node/file/([^/]*)/([^/]*)$ /php/node-file.php?file=$1&name=$2;                                    
    rewrite ^/node/file/([^/]*)/([^/]*)/?$ /php/node-file.php?file=$1&name=$2;
    

    现在您会注意到第一个 rewrite 语句是不必要的,因为第二个 rewrite 语句匹配带有和不带有尾随 / 的 URI。

    所以你只需要:

    rewrite ^/node/file/([^/]*)/([^/]*)/?$ /php/node-file.php?file=$1&name=$2;
    

    【讨论】:

    • 这行得通。我突然想到 .* 将匹配所有内容,包括斜线字符
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-18
    • 1970-01-01
    • 2012-12-14
    • 2018-11-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多