Eddie Jibson
Eddie Jibson

Reputation: 23

Nginx is downloading PHP files when trying to remove the extension

So, basically my current configuration is like below. Whenever I try and request the URL without the PHP extension it downloads it instead?

server {

      listen [::]:80;

      root myDirectory;

      index index.php index.html;

      server_name myDomain;

      location / {
        try_files $uri $uri/ $uri.php $uri.php$is_args$query_string =404;

      }

      location ~\.php$ {
        include snippets/fastcgi-php.conf;
        fastcgi_split_path_info ^(.+\.php)(/.+)$;
        include fastcgi_params;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_param SCRIPT_NAME $fastcgi_script_name;
        fastcgi_pass unix:/run/php/php7.1-fpm.sock;
      }

      location ~ /\ ht {
        deny all;
      }

    }

I've already done what a lot of other answers in other questions have suggested like editing the php7.1-fpm php.ini file:

cgi.fix_pathinfo=0

Any ideas?

Upvotes: 1

Views: 628

Answers (1)

Richard Smith
Richard Smith

Reputation: 49672

Your current use of try_files will not work. The file elements of the try_files statement are processed within the same location block, which is the wrong location for PHP files. See this document for more.

There are a number of solutions, but you could use a named location to perform an internal rewrite if the script file is found to exist.

For example:

location / {
    try_files $uri $uri/ @rewrite;
}
location @rewrite {
    if (-f $document_root$uri.php) { rewrite ^ $uri.php last; }
    return 404;
}
location ~ \.php$ {
    try_files $uri =404;

    include snippets/fastcgi-php.conf;
    include fastcgi_params;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    fastcgi_param SCRIPT_NAME $fastcgi_script_name;
    fastcgi_pass unix:/run/php/php7.1-fpm.sock;
}

See this caution on the use of if.

Upvotes: 1

Related Questions