Webmasters Stack Exchange is a question and answer site for pro webmasters. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

Given the following rewrite rule:

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

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

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

share|improve this question

migrated from serverfault.com Feb 26 '11 at 23:12

This question came from our site for system and network administrators.

up vote 2 down vote accepted
RewriteRule ^user/([0-9]+)(/?)$    /userprofile.php?user=$1   [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=$1   [L]

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

share|improve this answer
Is (?/) valid regex? It looks like a lookahead, but it's not. It seems like it ought to be /?, which would make the slash optional. – Lèse majesté Feb 27 '11 at 1:39
@Lèse majesté Mm, correct. It's reversed from what it should be. Fixed. – sysadmin1138 Feb 27 '11 at 1:42

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.