【问题标题】:Friendly URL with Apache Mod-Rewrite带有 Apache Mod-Rewrite 的友好 URL
【发布时间】:2019-04-30 11:18:45
【问题描述】:

现在已经阅读了一段时间,我已经接近但正在努力解决最后的障碍。

我有一个这样的网址: site.com/detail/123/some-description/maybe-some-more-description

我想成为的人

site.com/details.php?id=123

到现在为止

RewriteRule detail/(.*)/.*$ details.php?id=$1

根据这个 (https://htaccess.madewithlove.be/) 导致

details.php?id=123/some-text

如何去掉最后的一些文字?

【问题讨论】:

    标签: php regex apache mod-rewrite


    【解决方案1】:

    试试这个:

    • 正则表达式:(.*?detail)\/(\d+)\/.*
    • 替换:$1.php?id=$2

    这会导致site.com/detail.php?id=123

    他们都可以在Regex101 进行测试。

    • (.*?detail) 将站点基本 URL 与 details 匹配并捕获到组 $1
    • \/ 匹配斜线本身(必须转义)。
    • (\d+) 匹配号码并将其捕获到组$2
    • \/.* 匹配 URL 的其余部分,并且不将其包含在替换中会有所帮助。

    编辑:你介意detaildetails 之间的区别吗?

    【讨论】:

    • 很酷,我认为可以。不要认为我需要第一组,但这基本上就是我要寻找的:detail\/(\d+)\/.*
    • 所以我把它添加到了 Wordpress 中,它在 .htaccess RewriteRule 中生成了以下内容 ^(.*)\/details\/([a-zA-Z0-9_]+)\ /.* /detail/?id= [QSA,L] 这似乎不起作用我可以在这里看到它匹配 regex101.com/r/5hniR0/3
    • 这里似乎没问题:htaccess.madewithlove.be?share=7fe95f0b-48fc-5b3c-a296-3bfdbaa9… 但是当我通过 Apache / Wordpress 在本地运行它时似乎没有工作。有什么想法吗?
    【解决方案2】:

    在您的情况下,您似乎还有一组/text/

    更改您的规则: RewriteRule detail/(.*)/.*$ details.php?id=$1

    RewriteRule detail/(.*)/(.*)/.*$ details.php?id=$1

    如果你不知道有多少个斜线,你可以使用带有排除斜线的组[^\/]*

    RewriteRule detail/([^\/]*)/.*$ details.php?id=$1

    【讨论】:

    • 感谢您的快速回复。那么你需要知道后面的斜线的数量吗?例如,我不能说将第一个斜杠中的内容存储为 $1 并忽略它后面的所有内容?
    【解决方案3】:

    重写规则 ^([A-Za-z0-9]+)$ file.php?key=$1 [L,QSA]

    在锚标签中使用

      <a href="details/<?php $id?>">
    

    如果你想在变量中接收值 $value = $_REQUEST['key'];

    【讨论】:

      猜你喜欢
      • 2011-09-23
      • 1970-01-01
      • 2018-09-20
      • 2017-11-08
      • 1970-01-01
      • 2016-08-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多