Home > Enterprise >  NGINX - Handle both ID or Username
NGINX - Handle both ID or Username

Time:05-24

I have 2 urls like this:

1 - example.com/user/JohnFifty/

2 - example.com/user/45771/

Both work, but only one or the other. I want to allow both, which is enabled in the PHP code.

I have tried

if ($arg_id ~ ([\d] )[^\d]) {
   rewrite ^/user/([^/]*)/$ /user.php?id=$1 last;
}
rewrite ^/user/([^/]*)/$ /user.php?username=$1 last;

In order to detect the case, how can I make NGINX detect if the GET request is of a ID or string (username)?

Thank you

CodePudding user response:

This is exactly the case where a map block can be very helpful, being used among with the named capture groups:

map $id $id_type {
    ~^\d $   id;
    default  username;
}

server {
    ...
    rewrite ^/user/(?<id>[^/] )/$ /user.php?$id_type=$id;
    ...
}
  • Related