如何根据条件重写URL?

How to rewrite URL according to a condition?

我试图按照如下所述在 Apache 中编辑 URL,但我没有成功。

如果 URI 以字母 'a' 开头且第三位不是“7”且总位数为 6 那么 url http://example.com/a/123456/ 应该改写为 http://example.com/sixdigits.php

如果 URI 以字母 'b' 开头且第三位不是“7”且总位数为 4,则 url http://example.com/b/1234/ 应重写为 http://example.com/fourdigits.php

这是我对 .htaccess 文件的尝试。

RewriteRule ^a/[0-9]+/$  sixdigits.php 
RewriteRule ^b/[0-9]+/$  fourdigits.php

您能否尝试使用显示的示例进行以下、编写和测试。请确保在测试您的 URL 之前清除浏览器缓存。

RewriteEngine ON
RewriteRule ^a/([0-9]{2})([012345689])([0-9]{3})/?$ sixdigits.php [NC,L]
RewriteRule ^b/([0-9]{2})([012345689])([0-9])/?$  fourdigits.php [NC,L]

您可以使用:

  • [^7]表示NOT 7
  • \d表示[0-9]
  • {2}等表示two of the preceding character

因此:

If the URI starts with letter a and third digit is not 7 with total digits are 6 then url http://example.com/a/123456/ should be rewritten to http://example.com/sixdigits.php

RewriteRule ^a/\d{2}[^7]\d{3}/?$  sixdigits.php

If the URI starts with letter b and third digit is not 7 with total digits are 4 then url http://example.com/a/1234/ should be rewritten to http://example.com/fourdigits.php

RewriteRule ^b/\d{2}[^7]\d/?$  fourdigits.php

另一个正则表达式变体:

RewriteEngine On

RewriteRule ^a/\d{2}[^7\D]\d{3}/?$ sixdigits.php [L]

RewriteRule ^b/\d{2}[^7\D]\d/?$ fourdigits.php [L]
  • [^7\D] 将匹配除 7
  • 之外的任何数字