.htaccess url根据url的长度重写任何url

时间:2012-06-25 02:27:27

标签: php .htaccess mod-rewrite url-rewriting

我正在尝试重写所有4个确切字符的网址,但允许将其他网址重写为其名称+ .php

domain.com/a4Lv/ to domain.com/file.php?id=a4Lv
domain.com/longerThan4Chars/ to domain.com/longerThan4Chars.php

是否可以根据长度进行重写?

2 个答案:

答案 0 :(得分:2)

这应该有效。我更喜欢指定允许哪些字符(第一个选项)但是如果你想允许任何字符,请使用第二个

RewriteRule ^([a-zA-Z0-9]{4})(/?)$ /file.php?id=$1 [QSA,L]
RewriteRule ^(.{4})(/?)$ /file.php?id=$1 [QSA,L]

故障:

[a-zA-Z0-9]  limits it to letters and numbers
{4}          the length of the id
(/?)         optional trailing slash

答案 1 :(得分:1)

是的,您可以制作正则表达式来处理匹配中的字符数:

# for exactly 4 characters:
RewriteRule ^(.{4})/?$ /file.php?id=$1 [L]

# for more than 4 (need to exclude things ending with php)
RewriteCond %{REQUEST_URI} !\.php$
RewriteRule ^(.{4}[^/]+)/?$ /$1.php [L]