Nginx downloads PHP files, not executing
How to fix Nginx downloading PHP files instead of executing them error.
On this page
The error manifests on Nginx web server when PHP files are being force downloaded instead of being executed. For example, when visiting
mydomain.com/index.php
, instead of seeing the homepage of the website, the
index.php
file is being downloaded to the user's device.
PHP configuration to be in the correct server {} block directive
Make sure that your
nginx.conf
configuration file includes the PHP configuration inside the website
server {}
block directive and not in any other block directives:
server {
listen 80;
server_name mydomain.com;
location ~ \.php$ {
fastcgi_pass unix:/var/run/php-fpm.sock;
}
}
server {
listen 80 default_server;
}
Verify the value of fastcgi_pass parameter
In
nginx.conf
configuration file, at the
server {}
block directive, verify the value of the
fastcgi_pass
parameter.
Your PHP-FPM service may use
9000
port:
server {
location / {
fastcgi_pass 127.0.0.1:9000;
}
}
Or PHP-FPM may use the
.sock
socket file:
server {
location / {
fastcgi_pass unix:/var/run/php-fpm.sock;
}
}
If you use the
php-fpm.sock
file, make sure that the
cgi.fix_pathinfo
parameter is set to
0
in
php.ini
:
vi /etc/php5/fpm/php.ini # PHP 5
vi /etc/php/7.0/fpm/php.ini # PHP 7
Edit the
cgi.fix_pathinfo
to be uncommented and set to
0
:
cgi.fix_pathinfo = 0
Include FastCGI configuration
In
nginx.conf
configuration file, make sure your PHP-FPM service is configured properly:
server {
location ~ \.php$ {
include snippets/fastcgi-php.conf;
fastcgi_pass unix:/var/run/php-fpm.sock;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
}
}
Incorrect ownership
Check the username who runs Nginx:
ps aux | grep nginx
Edit the PHP-FPM configuration file. On Ubuntu systems, the path is:
vi /etc/php5/fpm/php.ini
Other possible locations can be:
/etc/php5/fpm/pool.d/www.conf
Set the username and group that will run Nginx and PHP-FPM:
user = www-data
group = www-data
listen.owner = www-data
listen.group = www-data
listen.mode = 0660
Replace
www-data
with the username that runs Nginx.
Missing ?query_string
If you use the
try_files
parameter for PHP framework integrations (WordPress, Larevel) in the
nginx.conf
configuration file, make sure you use the full path to
index.php
with
?query_string
:
server {
location / {
try_files $uri $uri/ /index.php?$query_string;
}
}