NGINX rewrite requests to file outside root

2019-07-13 03:41发布

Currently I'm running webprojects with the following directory structure (simplified):

  • project_folder/
    • public/
    • root/
    • index.php

What I want to do is set the root in the server block to:

root /project_folder/root/;

But when a request location does not exists I want it to forward the request to project_folder/index.php. I tried the following:

try_files $uri ../index.php?$query_string;

But this doesn't seem to work.

The same goes for a request that starts with $document_root/public/* which need to be forwarded to: $document_root/../public/*

I did manage this by adding a index.php in the /project_folder/root/ folder which includes the /project_folder/index.php. For the public folder I created a symlink. I could probably solve this by adding an alias for the location /public/ however I'm trying to keep my config as generic as possible.

I'm trying to prevent setting the project_folder as a root folder as it sometimes contains files I prefer not to be accessed from the web. Introducing the 'root' folder is new but I'm trying to do this as efficient as possible. Existing webprojects do not have the root folder yet.

Is what I'm trying to do possible and how would I be able to achieve this.

Thanks in advance.

1条回答
狗以群分
2楼-- · 2019-07-13 03:48

Usually PHP files are processed by a location ~ \.php$ block (or similar). I assume that index.php is not the only PHP file in your application, and to process PHP files within the /root/ directory structure, that location will need to use root /project_folder/root.

You can specify a different root for URIs which begin /public and use a named location to execute the out-of-root index.php file.

Something like this:

root /project_folder/root;

location / {
    try_files $uri $uri/ @index;
}

location /public {
    root /project_folder;
}

location @index {
    include fastcgi_params;
    fastcgi_param SCRIPT_FILENAME /project_folder/index.php;
    fastcgi_pass ...;
}

location ~ \.php$ {
    try_files $uri =404;

    include fastcgi_params;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    fastcgi_pass ...;
}
查看更多
登录 后发表回答