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.
1 Answer
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.
{1,35}+
mean? "1-35" or "1 or more"?