Nginx location configuration (subfolders)

To access a path like /var/www/mysite/manage/public with a URI like /manage, you will need to use alias rather than root. See this document for details.

I am assuming that you need to run PHP from both roots, in which case you will need two location ~ \.php blocks, see example below. If you have no PHP within /var/www/mysite/static, you can delete the unused location block.

For example:

server {
    listen 80;
    server_name  example.org;
    error_log /usr/local/etc/nginx/logs/mysite/error.log;
    access_log /usr/local/etc/nginx/logs/mysite/access.log;

    root /var/www/mysite/static;
    index index.html;

    location / {
    }
    location ~ \.php$ {
        try_files $uri =404;
        fastcgi_pass 127.0.0.1:9000;

        include fastcgi_params;
        fastcgi_param SCRIPT_FILENAME $request_filename;
        fastcgi_param SCRIPT_NAME $fastcgi_script_name;
    }

    location ^~ /manage {
        alias /var/www/mysite/manage/public;
        index index.php;

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

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

            include fastcgi_params;
            fastcgi_param SCRIPT_FILENAME $request_filename;
            fastcgi_param SCRIPT_NAME $fastcgi_script_name;
        }
    }
}

The ^~ modifier causes the prefix location to take precedence over regular expression locations at the same level. See this document for details.

The alias and try_files directives are not together due to this long standing bug.

Be aware of this caution in the use of the if directive.

Leave a Comment