mod 重写正则表达式

mod 重写正则表达式

计划是将 domain.com/chat2/roomnumber 重定向到 domain.com/chat2/index.php?room_id=roomnumber。

这是我无法正常工作的代码:

     RewriteEngine on
     RewriteRule  ^/chat2/([a-z0-9_-]+)/$ /index.php?room_id=$1 [NC,L]
     RewriteRule  ^/chat2/([a-z0-9_-]+)$ /index.php?room_id=$1 [NC,L]

我被转到了 404 页面。我猜问题出在我放置 ^ 的位置,但我也不确定。

答案1

阅读#2API Phases,我认为这是你的问题。在 .htaccess 文件中使用绝对 URL 进行重写对我来说是有效的。

RewriteRule ([a-z0-9_-]+)$ http://my.domain.com/index.php?room_id=$1 [NC,L]

答案2

你不想要:

RewriteRule  ^/chat2/([a-z0-9_-]+)/$ /chat2/index.php?room_id=$1 [NC,L]

因为您想重定向到/chat2/index.php?...

答案3

尝试这个:

Options +FollowSymlinks
RewriteEngine On
RewriteBase /chat2/
RewriteRule  ^/chat2/([a-zA-Z0-9_-]+)/?$ /index.php?room_id=$1 [NC,L]

答案4

RewriteRule 的经验法则是,如果前两个字符是“^/”,则第三个字符最好是一个问号,以使正斜杠成为可选项。

^/?chat...

不过,这可能不是你的问题。查看你的重写日志,第一行表明在应用模式之前,URI 被剥离为“asdf”。你读这些前缀行的方式是,“->”之后的任何内容都是模式要匹配的内容。

因此,对于你的情况,你的 RewriteRule 应该看起来像这样

RewriteRule ^([a-z0-9_-]+)/?$ index.php?room_id=$1 [NC,L]

如果您使用的是现代版本的 Apache,我猜是因为我不相信 + (一个或多个)量词在早期版本的 mod_rewrite 中可用,您可以在模式中使用与 Perl 兼容的正则表达式语法,包括诸如“\d”之类的简写来表示“0-9”。

RewriteRule ^([a-z\d_-]+)/?$ index.php?room_id=$1 [NC,L]

相关内容