How to configure nginx for a subdirectory?

I have a VPS running CentOS 7 and Nginx, with a WordPress website hosted on it. I’m now trying to build an API system in the ‘api’ subdirectory, but I’m having trouble configuring Nginx to point to the correct subdirectory. I plan on using WordPress SHORTINIT to make the API faster, but my existing WordPress configuration seems to be overwriting the ‘api’ subdirectory.

I have a location block for WordPress like below.

location / {
    try_files $uri $uri/ /index.php?$args;
}

location ~ \.php$ {
    include fastcgi_params;
    fastcgi_intercept_errors on;
    fastcgi_pass unix:/tmp/php-cgi.socket;
}

How can I properly configure Nginx to allow me to access the ‘api’ directory and execute PHP scripts inside it?

Assuming you want to configure nginx for a subdirectory of a domain (e.g. example.com/api ), you can use the following nginx configuration with your existing configuration:

location /api/ { 
  alias /var/www/wordpress/api; 
  try_files $uri $uri/ @api;
}
location @api {
  rewrite /api/(.*)$ /api/index.php?/$1 last;
}

By using this configuration, you should be able to access the API at http://example.com/api/ . Note that you may need to adjust the file paths and server names in the configuration to match your specific setup.

I think only setting up the alias should work.

location /api/ { 
  alias /var/www/wordpress/api; 
}