Wednesday, November 7, 2018

Running php site with php5-fpm behind nginx (centos 7)

If you're using latest version of nginx nginx-1.14.1-1.el7_4.ngx.x86_64, then by default in /etc/nginx/ you will have this files:

[centos@ip-172-31-37-214 ~]$ ls -la /etc/nginx
total 56
drwxr-xr-x.  3 root root 4096 Nov  7 07:41 .
drwxr-xr-x. 91 root root 8192 Nov  7 07:28 ..
drwxr-xr-x.  2 root root   89 Nov  7 07:37 conf.d
-rw-r--r--.  1 root root 1007 Nov  6 14:04 fastcgi_params
-rw-r--r--.  1 root root 2837 Nov  6 14:04 koi-utf
-rw-r--r--.  1 root root 2223 Nov  6 14:04 koi-win
-rw-r--r--.  1 root root 5170 Nov  6 14:04 mime.types
lrwxrwxrwx.  1 root root   29 Nov  7 07:28 modules -> ../../usr/lib64/nginx/modules
-rw-r--r--.  1 root root  643 Nov  6 13:54 nginx.conf
-rw-r--r--.  1 root root  636 Nov  6 14:04 scgi_params
-rw-r--r--.  1 root root  664 Nov  6 14:04 uwsgi_params
-rw-r--r--.  1 root root 3610 Nov  6 14:04 win-utf

But in order to run php site, you will need to tweak fastcgi_params. By default it contains this:
fastcgi_param  QUERY_STRING       $query_string;
fastcgi_param  REQUEST_METHOD     $request_method;
fastcgi_param  CONTENT_TYPE       $content_type;
fastcgi_param  CONTENT_LENGTH     $content_length;

fastcgi_param  SCRIPT_NAME        $fastcgi_script_name;
fastcgi_param  REQUEST_URI        $request_uri;
fastcgi_param  DOCUMENT_URI       $document_uri;
fastcgi_param  DOCUMENT_ROOT      $document_root;
fastcgi_param  SERVER_PROTOCOL    $server_protocol;
fastcgi_param  REQUEST_SCHEME     $scheme;
fastcgi_param  HTTPS              $https if_not_empty;

fastcgi_param  GATEWAY_INTERFACE  CGI/1.1;
fastcgi_param  SERVER_SOFTWARE    nginx/$nginx_version;

fastcgi_param  REMOTE_ADDR        $remote_addr;
fastcgi_param  REMOTE_PORT        $remote_port;
fastcgi_param  SERVER_ADDR        $server_addr;
fastcgi_param  SERVER_PORT        $server_port;
fastcgi_param  SERVER_NAME        $server_name;

# PHP only, required if PHP was built with --enable-force-cgi-redirect
fastcgi_param  REDIRECT_STATUS    200;

Now we need to add there one setting, but it's better to create new file:

sudo cp /etc/nginx/fastcgi_params /etc/nginx/fastcgi.conf

Then open /etc/nginx/fastcgi.conf and append this line at the top:

fastcgi_param  SCRIPT_FILENAME    $document_root$fastcgi_script_name;


Now in your server block you can use something like this to run your php site:
server {
...
        location ~ \.php$ {
                fastcgi_pass unix:/var/run/php5-fpm.sock;

                #include fastcgi_params;
                include fastcgi.conf;
        }
}

That's it. Now it should work.

No comments:

Post a Comment