Nginx subdirectory root with PHP

I’m running nginx in a docker container. I want to have a subdirectory /web/ to access my personal files and projects. It should also support php.

Below is what I’m running with but keeps resulting in a 404. PHP is confirmed working since the same php block works on a subdomain but directly in a server{} block.

http {

    server {
        listen      443 ssl;

        # Mime types
        include /etc/nginx/confs/mime.types;

        # SSL
        include /etc/nginx/confs/nginx-ssl.conf;

        # Proxy to organizr
        # This works
        location / {
            proxy_pass http://organizr/;
            proxy_set_header Host $http_host;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header X-Forwarded-Proto $scheme;

            # HTTP 1.1 support
            proxy_http_version 1.1;
            proxy_set_header Connection "";

        # Root folder for my personal files/projects
        # Doesn't work
        location /web {
            index index.php index.html;
            root /etc/nginx/www;

            location ~ \.php$ {
                try_files $uri =404;
                fastcgi_split_path_info ^(.+\.php)(/.+)$;
                fastcgi_pass php:9000;
                fastcgi_index index.php;
                include fastcgi_params;
                fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
                fastcgi_param PATH_INFO $fastcgi_path_info;

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

If your files are in /etc/nginx/www you will need to use an alias directive, rather than a root directive. See this document for details.

For example:

location ^~ /web {
    index index.php index.html;
    alias /etc/nginx/www;

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

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

        fastcgi_pass php:9000;
        include fastcgi_params;
        fastcgi_param SCRIPT_FILENAME $request_filename;

Use $request_filename to obtain the correct path to the aliased file. Avoid try_files with alias due to this issue. See this caution on the use of if.

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from or, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply