-1

My project directory structure is as follows:

/var/www/mysite/ backend/ frontend/

where frontend/ contains simple html and js files, and backend/ is a wordpress site. I expose wordpress data to a REST api endpoint for the frontend.

I want to have mysite.com show the html/js files and all REST api calls are made to mysite.com/api which are the wordpress site files. (so mysite.com/api/wp-admin will also work as normal).

I am having trouble configuring nginx to make this possible. This is my current configuration:

server {
  listen                *:80;

  server_name           mysite.com www.mysite.com;

  access_log            /var/log/nginx/mysite.access.log;
  error_log             /var/log/nginx/mysite.error.log;

  root  /var/www/mysite/frontend;

  location / {
    index  index.html index.htm index.php;
  }

location ^~ /api {
    root /var/www/mysite/backend;

    index index.php;
    try_files $uri $uri/ /../backend/index.php?$args;

    location ~ \.php$ {
      fastcgi_split_path_info ^(.+\.php)(/.+)$;
      # NOTE: You should have "cgi.fix_pathinfo = 0;" in php.ini

      # With php5-cgi alone:
      fastcgi_pass 127.0.0.1:9000;
      # With php5-fpm:
      #fastcgi_pass unix:/var/run/php5-fpm.sock;
      fastcgi_index index.php;
      include fastcgi_params;
    }
}

  sendfile off;
}

This just downloads the index.php file from wordpress when I try to access the URL mysite.com/api. Any help is appreciated, thanks.

Organic67
  • 1
  • 1

2 Answers2

0

The fundamental problem is that your configuration assumes that WordPress is installed at /var/www/mysite/backend/api. Using the root directive, the URI prefix is always part of the local pathname.

Use the alias directive to remove the /api element from the pathname. For example:

location ^~ /api {
    alias /var/www/mysite/backend;

    index index.php;
    if (!-e $request_filename) { rewrite ^ /api/index.php last; }

    location ~ \.php$ {
        if (!-f $request_filename) { return 404; }

        include fastcgi_params;
        fastcgi_param SCRIPT_FILENAME $request_filename;
        fastcgi_pass 127.0.0.1:9000;
    }
}

We avoid using try_files with alias due to this long standing issue. See this caution on the use of if

Richard Smith
  • 12,834
  • 2
  • 21
  • 29
0

You can do the below for WP in a sub-folder:

    location /backend {
            rewrite ^(/[^/]+)?(/wp-.*) /backend/$2 break;
            rewrite ^/backend/(.*)$ /backend/index.php?q=$1 last;
    }
Dario Zadro
  • 101
  • 2