【问题标题】:Htaccess - How to remove path without query string after last slash on urlHtaccess - 如何在 url 上的最后一个斜杠后删除没有查询字符串的路径
【发布时间】:2018-08-21 04:07:26
【问题描述】:

我想在 url 上的最后一个斜杠之后删除没有查询字符串的路径。

比如有一个url: https://www.example.com/example.php/fakepath/fakepath2/fakepath3?id=123

我想在.htaccess 文件中添加一个重写规则,并将原始 url 重定向到这个 url: https://www.example.com/example.php?id=123

因为我发现了这个问题:

这是一个正确的网址:http://www.twhappy.com/index.php?action=blog&category=6

如果我在index.php 之后添加斜杠,则网址将是http://www.twhappy.com/index.php/?action=blog&category=6

如果我在index.php 之后添加假路径:

http://www.twhappy.com/index.php/?action=blog&category=6 http://www.twhappy.com/index.php/fakepath/?action=blog&category=6 http://www.twhappy.com/index.php/fakepath/fakepath2/fakepath3/?action=blog&category=6

这些网址在我添加了假路径后就可以访问了。

所以,我想要一个重写规则将它们重定向到正确的 url。

对这个案子有什么想法吗?

非常感谢。

【问题讨论】:

  • "这些 url 在我添加了假路径后可以访问" AcceptPathInfo Off 禁用它。尝试使用奇怪 URL 的用户会收到 404。

标签: apache redirect


【解决方案1】:

更新答案

这是来自mod_aliasRedirectMatch 规则,它应该从.php 文件中删除任何PATH_INFO。这应该执行您所追求的重定向

# .htaccess
RedirectMatch permanent "^(.*\.php)/.*" "$1"

下面的旧答案

您当然不需要mod_rewrite。相反,启用AcceptPathInfo,例如

# .htaccess
AcceptPathInfo On

然后,/example.php/fakepath/fakepath2/fakepath3?id=123 的请求将解析为 example.php

var_dump($_GET);
var_dump($_SERVER['PATH_INFO']);

生产

array(1) {
  ["id"]=>
  int(123)
}
string(19) "/fakepath/fakepath2/fakepath3"

或者,如果您不想支持带有 PATH_INFO 的 URL,您可以将其关闭

# .htaccess
AcceptPathInfo Off

那么对包含 PATH_INFO 的 URL 的请求将导致 404。

【讨论】:

  • 菲尔,感谢您的耐心等待。但这个解决方案不是我想要的。我想要一个重写规则,将https://www.example.com/example.php/fakepath/fakepath2/fakepath3?id=123 重定向到https://www.example.com/example.php?id=123 再次感谢!
  • 我不确定你在说什么。您想要 URL 重写还是重定向?前者对用户不可见,后者要求用户客户端访问不同的 URL
  • Phil,是的,我想将http://www.example.com/xxx.php/fakepath/fakepath?id=123 重定向到http://www.example.com/xxx.php?id=123 在PHP 或Apache 服务器中,如果最终用户访问http://www.example.com/xxx.php/fakepath/fakepath?id=123,他将从http://www.example.com/xxx.php?id=123 获得相同的内容,所以我想重定向用户更正网址
  • @evenloooo 这些 URL 来自哪里?搜索引擎只关注链接
  • @evenloooo 我已经用 redirect 解决方案更新了我的答案。同样,您不需要mod_rewrite
【解决方案2】:

请尝试:

RewriteEngine On
RewriteRule ^example.php example.php/fakepath/fakepath2/fakepath3

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-01-03
    • 1970-01-01
    • 2017-05-03
    • 2021-02-06
    • 2015-02-21
    • 2020-09-08
    • 2013-08-11
    • 1970-01-01
    相关资源
    最近更新 更多