How to rewrite URL according to a condition?

Viewed 139

I was trying to get URLs edited in Apache as described below however I have not been successful.

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

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

Here is what I have tried with the .htaccess file.

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

3 Answers

Could you please try following, written and tested with shown samples. Please make sure you clear your browser cache before testing your URLs.

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]

Another regex variant:

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] will match any digit except 7

You can use:

  • [^7] to indicate NOT 7
  • \d to indicate [0-9]
  • {2} etc. to indicate two of the preceding character

Consequently:

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
Related