Mod rewrite 使用正则表达式的简单modrewrite规则

Mod rewrite 使用正则表达式的简单modrewrite规则,mod-rewrite,Mod Rewrite,这是我的网址 http://test.aDomain.com/x-61bff http://test.aDomain.com/x-ssmJhs54as65d4 http://test.aDomain.com/x-115545454 我的重写规则 RewriteEngine On RewriteBase / RewriteCond %{HTTP_HOST} ^www\.(.*)$ RewriteRule ^(.*)$ http://%1/$1 [L,R=301] RewriteRule ^c

这是我的网址

http://test.aDomain.com/x-61bff
http://test.aDomain.com/x-ssmJhs54as65d4
http://test.aDomain.com/x-115545454
我的重写规则

RewriteEngine On
RewriteBase /

RewriteCond %{HTTP_HOST} ^www\.(.*)$
RewriteRule ^(.*)$ http://%1/$1 [L,R=301]

RewriteRule ^create-account create-account.php [L]
RewriteRule ^account account.php [L]
RewriteRule ^impress impress.php [L]


RewriteRule ^(x\-[a-zA-Z0-9]+) redirect.php?code=$1 [L]
结果是

http://test.aDomain.com/redirect.php 
但是为什么呢?应该是

http://test.aDomain.com/redirect.php?code=x-61bff

我不明白。。。有人能帮忙吗?

主要是因为你把正则表达式搞错了:

  • 主机名和路径之间的
    /
    实际上是路径的一部分(例如,它是
    /x-61bff
    而不是
    x-61bff
    )。但是,您的正则表达式一开始只匹配
    x
    ,因此
    /x-61bff
    永远不会匹配

  • 减号在方括号内只有特殊含义(例如
    [a-Z]
    );在外面它只是另一个角色,没有必要逃避它

  • 因此,您的重写规则实际上应该如下所示:

    RewriteRule ^/(x-[a-zA-Z0-9]*) redirect.php?code=$1 [L]