I have the url such as example.com/page.php?username=test. I want to rewrite this url into something like: example.com/test only if test follows the following regual expression: /^[0-9a-zA-Z_-]{1,35}+$/, else 404 page.

  • I think something is wrong with the quantifier you specified, what should {1,35}+ mean? "1-35" or "1 or more"?
    – replay
    Jan 2 '14 at 16:22
  • I mean 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16...35.
    – user204126
    Jan 2 '14 at 16:23

This should work:

    location /page.php {
      if ($args ~ "^username=([0-9a-zA-Z_-]{1,35})$")
        set $username $1;
        rewrite . /$username last;
      return 404;

The trick is that in the location directive Nginx matches for the variable $uri, according to the documentation this variable does not include any get arguments. So the only way to achieve your goal is to first match for the uri /page.php, and then check the arguments in an if statement.

The reason why i had to do the set $username $1; instead of directly redirecting to the variable $1 is that the rewrite directive itself matches for sub strings of the given pattern, so it overwrites the $[0-9] variables. So I had to use the temporary $username variable to keep the username.

You might want to do something else than return 404; in the case where somebody gets into the location /page.php but the value of the username parameter does not match the regular expression.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy