PHP config doesnt work together with alias directive

Inside my server {} block, I have included a php.conf file, which works fine for all locations {} and subdirectories inside this block. But when a location block uses a alias directive, instead of the default root directive, the php files will be downloaded, instead of executed.

so my server block, looks like this:

server {
root /var/www/html;
# some other unrelated stuff

location / {
    try_files $uri $uri/ =404;
    rewrite ^(/)$ https://$host:$server_port/somesubdir/ permanent;
    limit_except GET HEAD POST { deny all; }
    return 444;
}

location /notworking {
    limit_except GET HEAD POST { deny all; }
    alias /var/www/somedir/subdir;
    # include snippets/php.conf;

location /test {
    location /test/test {
    # some location stuff
    }
}

include snippets/php.conf;
}

When i now use the browser an go to http(s)://mydomain.com/test/test/test.php, all is fine. PHP will be executed. But when i go to http(s)://mydomain.com/notworking/test.php, a download is started with the contents of test.php, instead of execute the php file. If i remove the comment sign from # include snippets/php.conf; and i go to http(s)://mydomain.com/notworking/test.php, PHP is executed instead of downloaded.

snippets/php.conf looks like:

location ~ \.php$ {
    fastcgi_split_path_info ^(.+\.php)(/.*)$;
    # fastcgi_split_path_info ^(.+\.php)(/.+)$;
    fastcgi_pass            unix:/run/php/php8.2-fpm.sock;
    fastcgi_index           index.php;
    fastcgi_param           SCRIPT_FILENAME $request_filename;

    include fastcgi_params;
}

Is there some way, to have a global php configuration, where i don’t need to include it again, only because the only difference is the alias directive?

As my usual disclaimer, I am not an NGINX Guru. However, when I look at this and did some digging, I think I can maybe point in the right direection.

I think this is occurring because the alias directive changes th way NGINX handles the file path. Trying to parse the docs, it looks like the SCRIPT_FILENAME has to exactly and correctly reflact the aliased path, which won’t happen with a global included php.conf.

To have a global PHP configuration that works with both root and alias directives without needing to include php.conf in each location block, you can modify the php.conf to dynamically handle the path based on whether an alias or root is used.

Also make sure that the php.conf is included at the server level not in individual location blocks.

Check out the doocusmentaion that might help:

nginx.org/en/docs/http/ngx_http_core_module.html#alias

nginx.org/en/docs/http/ngx_http_fastcgi_module.html#fastcgi_param

Hope this helps.

Many thx. Indeed, this pointed my in a good direction. I set now first the root or alias path to a variable and later on use this variable. There is a good example at https://serverfault.com/questions/795248/nginx-primary-script-unknown-fastcgi-param-alias

2 Likes