How to Install Nginx, PHP, and MySQL on a Debian Cloud Server?

31-01-2024 02:17:26

The LEMP stack, comprising Linux, Nginx, MySQL/MariaDB, and PHP, is analogous to the LAMP platform, with the key distinction being the substitution of the Apache Web server with Nginx. Nginx offers numerous advantages over other Web servers in terms of performance and security.

Installing Software

Install Nginx, MariaDB, and PHP using a single command.

$ sudo apt install nginx mariadb-server php-fpm php-mysql

Configuring Nginx

Edit the site configuration file, replacing "example.com" with your actual domain name.

$ sudo nano /etc/nginx/sites-available/example.com

In the configuration file, add the following code, also substituting "example.com" with your actual domain name.

server {
        listen 80;
        listen [::]:80;

        server_name example.com;

        root /var/www/html;
        index index.html index.htm index.php;

        location / {
                try_files $uri $uri/ =404;
        }

        location \.php$ {
                include snippets/fastcgi-php.conf;
                fastcgi_pass unix:/run/php/php7.3-fpm.sock;
        }
}

Activate the configuration document and reload Nginx.

$ sudo ln -sf /etc/nginx/sites-{available,enabled}/example.com
$ sudo systemctl reload nginx

Configuring MariaDB

Run the MariaDB installation script.

$ mysql_secure_installation

Respond to the prompts as per the instructions, typically default settings suffice.

Enter current password for root (enter for none):
Set root password? [Y/n] 
Remove anonymous users? [Y/n]
Press enter to disable root logins from remote machines.
Disallow root login remotely? [Y/n]
Remove test database and access to it? [Y/n]
Reload privilege tables now? [Y/n]

Testing the Server

Create a PHP test script.

$ sudo nano /var/www/html/test.php

Insert the following code and save.

<?php
phpinfo();

Then, access the script in a browser at: https://example.com/test.php. If you can see the PHP version information, it indicates successful configuration.

Finally, delete the test script and commence the formal deployment of your application.

$ sudo rm -f /var/www/html/test.php