PHP FastCGI – Nginx Projects in Subfolders

fastcginginxPHP

I'm getting frustrated with my nginx configuration and so I'm asking for help in writing my config file to serve multiple projects from sub-directories in the same root. This isn't virtual hosting as they are all using the same host value. Perhaps an example will clarify my attempt:

  • request 192.168.1.1/ should serve index.php from /var/www/public/
  • request 192.168.1.1/wiki/ should serve index.php from /var/www/wiki/public/
  • request 192.168.1.1/blog/ should serve index.php from /var/www/blog/public/

These projects are using PHP and use fastcgi.

My current configuration is very minimal.

server {
    listen 80 default;
    server_name localhost;

    access_log /var/log/nginx/localhost.access.log;

    root /var/www;
    index index.php index.html;

    location ~ \.php$ {
        fastcgi_pass  127.0.0.1:9000;
        fastcgi_index  index.php;
        fastcgi_param  SCRIPT_FILENAME /var/www$fastcgi_script_name;
        include fastcgi_params;
    }
}

I've tried various things with alias and rewrite but was not able to get things set correctly for fastcgi. It seems there should be a more eloquent way than writing location blocks and duplicating root, index, SCRIPT_FILENAME, etc.

Any pointers to get me headed in the right direction are appreciated.

Best Answer

Since your projects aren't actually in the same root, you must use multiple locations for this.

location /wiki {
    root /var/www/wiki/public;
}

location ~ /wiki/.+\.php$ {
    fastcgi_pass   127.0.0.1:9000;
    fastcgi_param  SCRIPT_FILENAME /var/www/wiki/public$fastcgi_script_name;
}

location /blog {
    root /var/www/blog/public;
}

location ~ /blog/.+\.php$ {
    fastcgi_pass   127.0.0.1:9000;
    fastcgi_param  SCRIPT_FILENAME /var/www/blog/public$fastcgi_script_name;
}

Also, put fastcgi_index in your fastcgi_params file and include it at server level, that way you keep your php locations as small as possible.