NGINX + PHP serve API from different root folder

I have started working on a spaguetti PHP code. I am not going to complaint or whatever, but I was asked to put some order into this chaotic project.

The first think it comes to mind is to start building an API and start build models for the most important entities of the project.

In the main file structure I need to create a new root folder for the API project.

public/api/index.php is the main file of the API.

To serve API calls like:

http://HOST/api/customers/{id}

you need to configure nginx accordingly

Add to the configuration file, normally named /etc/nginx/sites-availiable/default

change the location / {..} with the following:

location = / {
# First attempt to serve request as file, then
# as directory, then fall back to displaying a 404.
try_files $uri $uri/ =404;
}

# API Folder
location /api/ {
try_files $uri $uri/ =404;
}

You need a special ‘=’ modifier for the root location to work as expected.