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

Php .htaccess url根据url的长度重写任何url,php,.htaccess,mod-rewrite,url-rewriting,Php,.htaccess,Mod Rewrite,Url Rewriting,我正在尝试重写所有的URL,这些URL正好是4个字符,但允许将其他URL重写为其名称+.php domain.com/a4Lv/ to domain.com/file.php?id=a4Lv domain.com/longerThan4Chars/ to domain.com/longerThan4Chars.php 基于长度的重写是否可行?这应该可以。我更喜欢指定允许哪些字符(第一个选项),但如果您想允许任何字符,请使用第二个 RewriteRule ^([a-zA-Z0-9]{4})(/?

我正在尝试重写所有的URL,这些URL正好是4个字符,但允许将其他URL重写为其名称+.php

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

基于长度的重写是否可行?

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

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

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

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

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

# 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]

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

# 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]

这是一个正则表达式,任何事情都有可能:)@andrewtweber所以本质上我可以做一些类似于
RewriteRule/(..)/file.php的事情?$1
?这是一个正则表达式,任何事情都有可能:)@andrewtweber所以本质上我可以做一些类似
RewriteRule/(..)的事情/file.php?$1
?我忘了你问题的第二部分,但基本上你可以将
(.*)
重写为
$1.php
。由于前面的规则有
[L]
标志,这意味着这只会影响不完全是4个字符的内容,我忘记了问题的第二部分,但基本上您可以将
(.*)
重写为
$1.php
。由于前面的规则具有
[L]
标志,这意味着这只会影响长度不完全为4个字符的内容