trouble executing php scripts with nginx

lovesh asked:

My nginx config looks like this

server {
        listen       80;
        server_name  localhost;

        location / {
           root /var/www;
           index index.php index.html;
           autoindex on; 
        }

        location /folder1 {
           root   /var/www/folder1;
           index  index.php index.html index.htm;
           try_files $uri $uri/ index.php?$query_string;
        }

        location /folder2 {
           root   /var/www/folder2;
           index  index.php index.html index.htm;
        }

        location ~ .php$ {
            fastcgi_pass   127.0.0.1:9000;
            fastcgi_index  index.php;
            include        fastcgi_params;
            fastcgi_param  SCRIPT_FILENAME $document_root$fastcgi_script_name;
    }
}

The problem with the above setup is that i am not able to execute php files. Now as per my understanding of nginx config rules, when i am in my webroot(/) which is /var/www the value of $document_root becomes /var/www so when i request for localhost/hi.php the fastcgi_param SCRIPT_FILENAME becomes /var/www/hi.php and that is the actual path of the php script. But when i actully go to the url localhost/hi.php i get a message File not found. But when I go to the url localhost/hi.html i can see the html output of the page. So this means that there is a problem with the location block of php.

Similarly when i request for localhost/folder1/hi.php the $document_root becomes /var/www/folder1 because this is specified as the root in folder‘s location block so again the fastcgi_param SCRIPT_FILENAME becomes /var/www/folder1/hi.php. But when i actully go to the url localhost/folder1/hi.php i get a message File not found. But when I go to the url localhost/folder1/hi.html i can see the html output of the page. So again php are not being executed.

Please help?

My answer:


You need to remove the root lines from the two location /folder* blocks, and move the root /var/www to within the server block, not the location / block. This is one of the most common nginx misconfigurations.


View the full question and answer on Server Fault.

Creative Commons License
This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.