Sebastian Sulinski
Sebastian Sulinski

Reputation: 6045

Nginx config: route all .php files via index except if it contains a path to the file manager

I'm working on the new project, which will have many redirects from the old website uris. Many of the old uris contain the .php extension in the uri and Nginx tries to load them as a file rather than fall back to our redirect controller method.

To make it a bit more tricky, we are using wysiwyg editor with the file manager, which, when called - uses .php extension so this one needs to be excluded.

Effectively I would like it to work the way so that when I call for instance old uri such as /old-page/path/file.php it will route it via index.php but when I call /vendor/ckfinder/plugins/filemanager/dialog.php?... it will load the actual file.

I've seen this post, which doesn't really resolve what I'm after, but I think it's a good starting point How to remove both .php and .html extensions from url using NGINX?

My existing setup is

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

location ~ \.php$ {
    fastcgi_split_path_info ^(.+\.php)(/.+)$;
    fastcgi_pass unix:/var/run/php/php7.2-fpm.sock;
    fastcgi_index index.php;
    include fastcgi_params;
}

Any help would be much appreciated.

UPDATE

I tried @Richard Smith suggestion, which after reading the docs I think should work, but unfortunately, for whatever reason - it doesn't - here's what I tried:

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

location ~ \.php$ {
    try_files $uri /index.php?$query_string;
    fastcgi_pass unix:/var/run/php/php7.2-fpm.sock;
    include fastcgi_params;
}

So try_files checks if $uri exists - and if it doesn't it falls back to /index.php?$query_string;, which should point the request to index.php. Any idea what I might be missing here?

Upvotes: 1

Views: 1908

Answers (1)

Richard Smith
Richard Smith

Reputation: 49712

If the PHP files do not exist on the new server, the simplest solution is to redirect any non-existent PHP files to /index.php - just as you do for non-PHP URIs.

For example:

location / {
    try_files $uri $uri/ /index.php?$query_string;
}
location ~ \.php$ {
    try_files $uri /index.php?$query_string;
    fastcgi_pass unix:/var/run/php/php7.2-fpm.sock;
    include fastcgi_params;
}

The fastcgi_split_path_info and fastcgi_index statements and not required in this particular location block.

See this document for more.

Upvotes: 2

Related Questions