Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

NGINX – Handle both ID or Username

I have 2 urls like this:

1 – example.com/user/JohnFifty/

2 – example.com/user/45771/

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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;
    ...
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading