0

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.

I

JSON Internal Interface

html
html/api
html/api/v1
html/api/v1/getUsers.php

HTML External Interface

html
html/gui
html/gui/v1
html/gui/v1/get/users/1001

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]

1 Answer 1

1

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;
}
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, 2020 at 20:14

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .