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:
- Make sure that you have the
fastcgi_passdirective configured correctly in your Nginx configuration file. This directive specifies the address and port of the FastCGI server that will handle PHP requests. A typicallocation ~ \.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;
}- Check that the
try_filesdirective 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. - Check that the
fastcgi_indexdirective 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. - Make sure that the
rootdirective 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. - Check that the
indexdirective 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. - Make sure that the
includedirective is correctly set to include thefastcgi_paramsfile. This file contains a set of default FastCGI parameters that are used to process PHP requests. - 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 withsudo systemctl status php-fpm(orphp8.x-fpm). - 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.
- 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 nginxI 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.