Mobile app version of vmapp.org
Login or Join
Heady270

: Regex Needed to allow mod-rewrite rule to work either with or without trailing slash? Given the following rewrite rule: RewriteRule ^user/([^/]*)$ /userprofile.php?user= [L] How can I have it

@Heady270

Posted in: #Apache #ModRewrite

Given the following rewrite rule:

RewriteRule ^user/([^/]*)$ /userprofile.php?user= [L]


How can I have it work either with or without a trailing slash?

Bonus points, how can I verify ([^/]*) contains only numerals?

10.01% popularity Vote Up Vote Down


Login to follow query

More posts by @Heady270

1 Comments

Sorted by latest first Latest Oldest Best

 

@Pierce454

RewriteRule ^user/([0-9]+)(/?)$ /userprofile.php?user= [L]


The above rule should match on these conditions:


user/123
user/123/


It will not match:


user/fred
user/123fred
user/fred123


([0-9]+) means match any numeral with one or more digits.
(/?)$ means an optional match of a slash, followed by a mandatory end-of-string.

For extra credit, you can even use this:

RewriteRule ^user/([0-9]{1,9})(/?)$ /userprofile.php?user= [L]


Which tells it to match numbers between one and nine digits (the {1,9} thing). Useful as an input-validator.

10% popularity Vote Up Vote Down


Back to top | Use Dark Theme