4

I've looked at dozens of other questions and references on the web - and by all my calculations, my setup should work, but it doesn't.

I have nginx installation with php-fpm. If I try to access a .php file, it runs correctly and I get the correct results. I got this in my config file:

location ~ \.php$ {
    try_files $uri =404;
    fastcgi_pass unix:/var/run/php5-fpm.sock;
    include fastcgi_params;
    fastcgi_param SCRIPT_FILENAME  $document_root$fastcgi_script_name;
}

Now, I want to setup my web app so that /somedir/file automatically executes /somdir/file.php while still displaying /somdir/file in the browser's address bar. So I modified my config to contain the following:

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

This kind of works, that is, the server does access the .php file. Yet, instead of executing it using the existing location ~ \.php$ block above, it simply spits the php source code as the download into the browser. If I append the .php manually to the requested URL, then the php is executed.

It feels as if once the server matches try_files to $uri.php, it then does not do another pass at locations to see that what it needs to do with the php files. I tried putting the php block above and below the location /, but it makes no difference.

How can I get the php to be executed?

Aleks G
  • 936
  • 2
  • 8
  • 18

2 Answers2

6

Did you try with the rewrite directive? For example:

location / {
    try_files $uri $uri/ @extensionless-php;
    index index.html index.htm index.php;
} 

location ~ \.php$ {
    try_files $uri =404;
    fastcgi_pass unix:/var/run/php5-fpm.sock;
    include fastcgi_params;
    fastcgi_param SCRIPT_FILENAME  $document_root$fastcgi_script_name;
}

location @extensionless-php {
    rewrite ^(.*)$ $1.php last;
}

Source: http://www.tweaktalk.net/60/nginx-remove-php-file-extension-from-url

martintama
  • 181
  • 3
3

try_files always executes in current context, that's why it serves your php-scripts as plain files - current location lacks fastcgi_pass. try_files is evil because instead of straightforwardness it creates questionable blocks, avoid it.

In the same time regexp-locations have priority over ordinary locations, that's why nothing changes when you reverse the order.

Personally I think that hiding .php extensions from address bar is useless, as it adds more code to the configuration file.

drookie
  • 8,625
  • 1
  • 19
  • 29
  • 1
    Thanks for the reply. php extension is not hidden for security - these are API calls used by a number of external applications that I don't control. API used to be written in something else and later rewritten in php. I am in no position to require developers of all external systems that communicate with my api to change their code to new urls. Hence I need to get this working. What should I change in my config? – Aleks G Feb 19 '16 at 10:02
  • Add `fastcgi_pass` etc on the same level as first `try_files`. – drookie Feb 19 '16 at 12:33