Skip to content
Advertisement

Is it possible to have web index outside public html?

Say a website has this folder structure

/index.php
/<public>
   dikpic.jpeg

And when someone visits the website I want the physical web root to point to /public, like mywebsite.com/dikpic.jpeg

(without url rewrites).

This can be achieved with the root /myuser/public; command.

But I also want to load the index.php file from outside this directory:

index /myuser/index.php;

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

location ~* .php$ {
    fastcgi_pass unix:/run/php/php7.4-fpm-myuser.sock;
    include         fastcgi_params;
    fastcgi_param   SCRIPT_FILENAME    $document_root$fastcgi_script_name;
    fastcgi_param   SCRIPT_NAME        $fastcgi_script_name;
}

The problem is with the location try files block that assumes / is the web root 🙁

Any way around this?


I should also point out that the index.php is the only script on the website. So I don’t really care if any other requests for .php files are ignored. The index.php handles url rewriting stuff…

Advertisement

Answer

You can use an additional location block for that, although it doesn’t seems an elegant solution to me:

location ~* .php$ {
    fastcgi_pass unix:/run/php/php7.4-fpm-myuser.sock;
    include         fastcgi_params;
    fastcgi_param   SCRIPT_FILENAME    $document_root$fastcgi_script_name;
    fastcgi_param   SCRIPT_NAME        $fastcgi_script_name;
}

location = /index.php {
    fastcgi_pass unix:/run/php/php7.4-fpm-myuser.sock;
    include         fastcgi_params;
    fastcgi_param   SCRIPT_FILENAME    /full/path/to/your/index.php;
    fastcgi_param   SCRIPT_NAME        /index.php;
}

Exact matching locations have a priority over regex matching ones, so the first block will be used for any PHP file request except the /index.php. You don’t even need to define a root for the second location, setting right SCRIPT_FILENAME FastCGI parameter value will be enough.

Update

I didn’t notice the very last sentence of your question, but if you didn’t care for any other PHP files, only the second block location = /index.php { ... } will be enough.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement