Configuring Nginx to run PHP on ubuntu16

Default nginx setting when installed

path: /etc/nginx/sites-enable/default

# Default server configuration
#
server {
	listen 80 default_server;
	listen [::]:80 default_server;

	root /var/www/html;
	# Add index.php to the list if you are using PHP
	index index.html index.htm index.nginx-debian.html;

	server_name _;

	location / {
		# First attempt to serve request as file, then
		# as directory, then fall back to displaying a 404.
		try_files $uri $uri/ =404;
	}

	# pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
	#
	#location ~ \.php$ {
	#	include snippets/fastcgi-php.conf;
	#
	#	# With php7.0-cgi alone:
	#	fastcgi_pass 127.0.0.1:9000;
	#	# With php7.0-fpm:
	#	fastcgi_pass unix:/run/php/php7.0-fpm.sock;
	#}

}

 

As the line number 8 suggest to add index.php if we are running php. Let’s accomplish that by changing the line 9 to

index index.php index.html ;

Next stage:

Now we need to set the nginx to parse the PHP. So when it finds the php, we have a choice to decide what will handle the PHP for nginx. Either the option in line number 25 or line number 27.

fastcgi_pass 127.0.0.1:9000; 

means we want the server running on 9000 port to handle the php.

fastcgi_pass unix:/run/php/php7.0-fpm.sock;

means we want the phpfpm to handle the php. This is the reason why we have installed the phpfpm. So we will use the second option here. I normally use the first option when I have the phpfpm serving from different container but here we have it installed on same machine, thus we go with second option. Now after removing comment from line number 21 it will finally look as follow.

 

server {
	listen 80 default_server;

	root /var/www/html;
	# Add index.php to the list if you are using PHP
	index index.php index.html

	server_name _;

	location / {
		# First attempt to serve request as file, then
		# as directory, then fall back to displaying a 404.
		try_files $uri $uri/ =404;
	}

# pass the PHP scripts to FastCGI server listening
	location ~ \.php$ {
	  # With php7.0-fpm:
          fastcgi_pass unix:/run/php/php7.0-fpm.sock;
	}
}

Restart the nignx or reload it

service nginx reload  or service nginx restart

Create a simple index.php file inside the root path set in the nginx to test if the nginx is serving the php or not.

Leave a Reply