I have spent several hours trying to figure out in NGINX what is otherwise and incredibly trivial task in Apache.

I am exhausted...

I have installed NGINX right out of the box.

html is the root folder.


JSON Internal Interface


HTML External Interface


I have a working location block which illustrates the final goal.

location = /get/users/1001 {

  add_header Content-Type text/plain;
  return 200 'This non physical URL path needs to point to html/api/v1/getUsers.php?userId=1001';


How can a person accomplish this. I am seriously about to go back to Apache and never look back.

Here is a sample of how I perfectly accomplish this task in Apache by placing the following Apache directives inside an .htaccess file located in html/gui/v1

Options +FollowSymLinks
RewriteEngine On

RewriteRule ^get/users/(\d+)/?$ getUser.php?userId=$1 [L]

Nginx rewrite directive works almost identically as RewriteRule in Apache2. So all you need is:

location / {
    rewrite ^/get/users/(\d+)/?$ /getUsers.php?userId=$1 last;
location ~ \.php$ {
    # PHP-FPM config

or, if you prefer named captures:

location / {
    rewrite ^/get/users/(?<userId>\d+)/?$ /getUsers.php?userId=$userId last;

All URI paths are absolute.

Since you are mentioning regexp locations in your title, your example can be generalized to:

location ~ ^/get/users/(\d+)/?$ {
    add_header Content-Type text/plain;
    return 200 /getUsers.php?userId=$1;
  • Perfect! I have added /? at the end of (\d+) in case of the presence or absence of a trailing slash at the end. Now both match. – suchislife Mar 28 '20 at 20:14

Your Answer

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

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