【问题标题】:nginx rewrite url missing somethingnginx 重写 url 缺少一些东西
【发布时间】:2021-12-28 11:17:57
【问题描述】:

我在根目录下有多个动态 url,需要编写如下。例如

https://mv.test/review/4
https://mv.test/investment-banker/banking-products--004

第一个网址 /Reviews/ 工作正常,但第二个网址将进入 404 页面。我无法理解为什么它不起作用。

定位块

location / {
    try_files $uri $uri.html $uri/ @extensionless-php;
}
location @extensionless-php {
    rewrite ^(.*)$ $1.php last;
}

location /review/ {
    rewrite "^/review/([0-9]+)$" /review.php?id=$1 last;
}
location /store/ {
    rewrite "^/(.*)/(.*)$" /store.php?store_type=$1&store_owner=$2 last;
}

【问题讨论】:

  • 您的第一个示例 URI 与您的第一个位置块 location /review/ { ... } 不匹配,也许您的意思是 /review/4 而不是 /reviews/4?此外,您无需指定如何处理诸如/review/some-non-digital-string 之类的 URI,通常您希望显示一些自定义的“未找到”页面。您的第二个示例 URI /investment-banker/banking-products--004 显然与您的第二个位置块 location /store/ { ... } 不匹配,因为它不以 /store/ 前缀开头。
  • 嗨 @IvanShatsky,感谢您突出显示 /Reviews/ 错误。我已经纠正了。对于第二个 url,虽然文件名 {store.php} 当前位于根目录中,但我也尝试过,将其放入存储文件夹中。如果我将此重写代码放在根位置块下,那么也没有任何作用。
  • location /store/ 必须与 URL 匹配。所以它只匹配像 https://mv.test/store/... 这样的 URL 而不是 https://mv.test/investment... - 所以不清楚为什么你希望最后一个块重写第二个 URL。
  • 嗨@RichardSmith,我想用位于根目录的php脚本重写第二个url,名称为store.php。两个查询字符串investment-banker/banking-products--004 本质上是动态的,将变为 21 种不同类型的服务。虽然我能够使用https://mv.test/store/investment-banker/banking-products--004 成功重写 url。但我想改写为https://mv.test/investment-banker/banking-products--004

标签: nginx nginx-location


【解决方案1】:

显然https://example.com/investment-banker/banking-products--004location /store/不匹配,所以会被默认location处理,即location /

对于任何与服务器已处理的另一个合法 URI 不匹配的 foo/bar,您希望将 https://foo/bar 重写为 /store.php?store_type=foo&store_owner=bar

目前location @extensionless-php块会盲目地将URL重写为/foo/bar.php,无论PHP文件是否存在。

这可以通过if 块来改进。

例如:

location / {
    try_files $uri $uri.html $uri/ @extensionless-php;
}
location @extensionless-php {
    if (-f $document_root$uri.php) {
        rewrite ^(.*)$ $1.php last;
    }
    rewrite ^/([^/]+)/([^/]+)$ /store.php?store_type=$1&store_owner=$2 last;
}    
location /review/ {
    rewrite ^/review/([0-9]+)$ /review.php?id=$1 last;
}

【讨论】:

    猜你喜欢
    • 2015-09-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-02
    • 2021-08-04
    • 2013-10-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多