Last Updated on April 30, 2021 by Amit

Regex in RewriteRule
RewriteRule directive uses a Regular expression based pattern to match against URL path. In this post we will cover some basic and commonly used patterns that are most often used in RewriteRule.

RewriteRule basic regex

  • (.*) Catch-all and save (zero or more characters)
  • (.+) Catch-all and save (one or more characters)
  • ([a-zA-Z0-9]+) Catch-all alpha numbric Chars (A to Z , a-z and 0-9)
  • ([0-9]+) Catch-all numbric Chars in URI ( 0-9)
  • ([a-z]+) Catch-all lower case URI chars (a to z)

(.*) matches all characters in URI and saves the value in $1 variable which can be used in rule’s substitution string.

RewriteRule (.*) /file.php/$1 [R]

The rewrite rule above will redirect any URI to /file.php/anyURi . The pattern (.*) matches all URL paths including / (hompage). The $n variable holds whatever (.*) captures.

(.+) matches one or more characters in an URI string and saves the matched value in $1 variable.

RewriteRule (.+) /file.php/$1 [R]

The rule above will redirect /anyURI to /file.php/anyURI . The difference between + and * in the pattern is that + means to match one or more time . The minimum required character in URI is one while the * matches zero or more time. The pattern (.+) will not match your hompage “/” as the single “/” is treated as no char in RewriteRule.

([a-zA-Z0-9]+) matches alphabetical characters in URI. Only the characters you put inside [] are matched. A-Z matches UPPER CASE characters ranging from A-Z .

RewriteRule ([a-zA-Z0-9]+) /file.php/$1 [R]

Our RewriteRule above will match all uri of the following formats /thisuri , /ThisURI123 etc..

([0-9]+) matches a numbric URI string ie “/123” .

RewriteRule ^([0-9]+)$ /file.php/$1 [R]

The rule above will redirect example.com/123 to example.com/file.php/123 . The ^ indicates start of the URI string and $ indicates end of the string . If the ^ and $ are removed in the rule above then the rule will also redirect example.com/foo123 but the pattern will only capture numberic part of the uri “123”

^([a-z]+)$ matches lower case alphabetical URI characters ie. ” example.com/thisuri”

RewriteRule ^([a-z]+)$ /file.php/$1 [R]

I hope it was helpful. Thanks for reading.

How useful was this post?

Click on a star to rate it!

Average rating 0 / 5. Vote count: 0

No votes so far! Be the first to rate this post.