W3docs

Nginx serves .php files as downloads, instead of executing them

There are several reasons why Nginx may serve PHP files as downloads instead of executing them.

There are several reasons why Nginx may serve PHP files as downloads instead of executing them. Here are a few things you can try to troubleshoot the issue:

  1. Make sure that you have the fastcgi_pass directive configured correctly in your Nginx configuration file. This directive specifies the address and port of the FastCGI server that will handle PHP requests. A typical location ~ \.php$ block should look like this:
location ~ \.php$ {
    include fastcgi_params;
    fastcgi_pass unix:/run/php/php-fpm.sock; # or 127.0.0.1:9000
    fastcgi_index index.php;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    try_files $uri =404;
}
  1. Check that the try_files directive is present. This is the most common cause of PHP files being served as downloads. It ensures Nginx verifies the file exists before passing it to PHP-FPM, preventing directory traversal and execution errors.
  2. Check that the fastcgi_index directive is correctly set to the name of the PHP entry script. This directive specifies the default file that should be served when a directory is requested.
  3. Make sure that the root directive is correctly set to the root directory of your website. This directive specifies the root directory that should be used to search for the requested file.
  4. Check that the index directive is correctly set to the name of the PHP entry script. This directive specifies the default file that should be served when a directory is requested.
  5. Make sure that the include directive is correctly set to include the fastcgi_params file. This file contains a set of default FastCGI parameters that are used to process PHP requests.
  6. Check your PHP-FPM service status. Ensure the service is active and listening on the socket or port defined in fastcgi_pass. You can verify this with sudo systemctl status php-fpm (or php8.x-fpm).
  7. Check the permissions on your PHP files. Nginx may not be able to execute the PHP files if they are not readable or executable by the user that Nginx is running as.
  8. Check your Nginx error logs for any error messages that may provide more information about the issue.

After updating your configuration, test the syntax and reload Nginx:

sudo nginx -t && sudo systemctl reload nginx

I hope these suggestions help! If you are still having trouble, please provide more information about your Nginx configuration and any error messages you are seeing, and I will do my best to help.