Nginx and PHP configuration

Let's now configure Nginx and PHP on our web server machine. Log into the machine by running the vagrant ssh web1 command.

Once logged in, we need to finish configuring nginx. This can be done by editing the default config file with the following command:

sudo nano /etc/nginx/sites-available/default

We now need to add PHP into this file to allow nginx to handle PHP files and code. The first line we need to edit is the index file list, so find the following line:

index index.html index.htm index.nginx-debian.html;

Chanage it to this:

index index.php index.html index.htm index.nginx-debian.html;

The final change we need to perform is to add the PHP handling. This requires us to edit a block inside the main server {} block. The following snippet is the code we need to edit:

 #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;
#}

Change the preceding snippet to the following:

location ~ .php$ {
include snippets/fastcgi-php.conf;
# With php7.0-fpm:
fastcgi_pass unix:/run/php/php7.0-fpm.sock;
}

Now save and close the file. If you want to, you can use the sudo nginx -t command to test the code and syntax of the config file you have just edited. A successful message is as follows:

Let's now restart nginx to apply the new settings; to do so, run the following command:

sudo systemctl reload nginx

To confirm PHP has been installed and is working, create a test.php file within the /var/www/html/ directory. Within the test.php file, add the following lines:

<?php
phpinfo();
?>

Save the file and in your web browser on your host machine, open http://10.0.0.50/test.php . You should now see the PHP info page, as shown in the following screenshot:

While we're here, we should go back into the test.php file and edit its contents. So, we are now going to create a basic PHP script that connects to our MySQL database and retrieves some data. Edit the file to contain the following snippets:

<?php
$conn = new mysqli("10.0.0.51", "external", "password", "VagrantDatabase");
$result = $conn->query("SELECT VagrantText FROM VagrantTable WHERE VagrantId = 1");
while($row = $result->fetch_assoc()) {
echo $row['VagrantText'];
}
?>
This is a very basic script to help get you started. This script is not secure and does not necessarily follow the PHP best practices. It would not be recommended to use this script in a production environment.

Before we can continue, we must set up the MySQL server on our other Vagrant machine; otherwise, the PHP script will fail as there is no database available.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.140.185.170