http RewriteCond 和 RewriteRule

发布于 2025-01-05 18:54:11 字数 223 浏览 1 评论 0原文

我需要重写 URL,例如 http://www.example.com/search.php?abchttp://www.example.com/abc 使用下面的规则,但它不起作用,为什么不匹配?

RewriteCond %{REQUEST_URI} ^search.php
RewriteRule ^search.php?q=([-0-9a-zA-Z]+) $1

I need to rewrite URL like http://www.example.com/search.php?abc
to http://www.example.com/abc
using the rules below, but it doesn't work, why doesn't it match?

RewriteCond %{REQUEST_URI} ^search.php
RewriteRule ^search.php?q=([-0-9a-zA-Z]+) $1

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

鸠书 2025-01-12 18:54:11
  • %{REQUEST_URI} 始终以 / 开头。因此 RewriteCond %{REQUEST_URI} ^search.php 永远不会匹配。

  • 重写规则指令

    <块引用>

    Pattern 是 Perl 兼容的正则表达式。在第一个 RewriteRule 上,它应用于请求的(%-解码)URL 路径;后续模式将应用于最后匹配的 RewriteRule 的输出。

  • ? 表示在未转义时匹配一个或不匹配前一个字符。所以你的 ^search.php?q=... 将匹配:

    • search.phpq=...
    • search.phq=...

来自 PCRE 手册页

?扩展了(
也是 0 或 1 量词
还有量词最小化器

你必须这样做:

Options +FollowSymLinks
RewriteEngine On

RewriteCond %{ENV:REDIRECT_STATUS} 200
RewriteRule ^ - [L]

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-l
RewriteCond %{REQUEST_URI} ^/([\w]+)/?$ [NC]
RewriteRule ^ search.php?q=%1 [L,QSA]

RewriteCond %{REQUEST_URI} ^/search.php [NC]
RewriteCond %{QUERY_STRING} ^q=([\w\d-]+)$ [NC]
RewriteRule ^ /%1? [L,R=301]

  • %{REQUEST_URI} always has a / at the start. so RewriteCond %{REQUEST_URI} ^search.php will never match.

  • RewriteRule Directive

    Pattern is a perl compatible regular expression. On the first RewriteRule it is applied to the (%-decoded) URL-path of the request; subsequent patterns are applied to the output of the last matched RewriteRule.

  • ? means match for one or none of previous character when not escaped. So your ^search.php?q=... would match:

    • search.phpq=...
    • search.phq=...

from PCRE man pages

? extends the meaning of (
also 0 or 1 quantifier
also quantifier minimizer

You will have to do this:

Options +FollowSymLinks
RewriteEngine On

RewriteCond %{ENV:REDIRECT_STATUS} 200
RewriteRule ^ - [L]

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-l
RewriteCond %{REQUEST_URI} ^/([\w]+)/?$ [NC]
RewriteRule ^ search.php?q=%1 [L,QSA]

RewriteCond %{REQUEST_URI} ^/search.php [NC]
RewriteCond %{QUERY_STRING} ^q=([\w\d-]+)$ [NC]
RewriteRule ^ /%1? [L,R=301]

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文