How to setup WordPress with Nginx, MySQL, and PHP in Ubuntu 20.04 the right way

Spread the love

Introduction

WordPress is one of the most famous content management systems (CMS) on the web right now, permits clients to set up adaptable web journals and sites utilizing a MySQL backend with PHP processing. WordPress has seen an extraordinary reception rate among new and experienced Web Designers and is an incredible decision for making a site ready proficiently. After an underlying arrangement, practically all organization for WordPress sites should be possible through its graphical user interface — these elements and more pursue WordPress an extraordinary decision for sites worked to scale.

In this instructional exercise, you’ll zero in on getting an example of WordPress set up on a LEMP stack (Linux, Nginx, MySQL, and PHP) for a Ubuntu 20.04 server. And we will set up all this while keeping security and operations in mind.

Prerequisite

Prerequisites to set up WordPress on Ubuntu will include setting up Ubuntu Server 20.04 with a public IP. The server shall have at least 1 vCPU, 2GB RAM, and 30GB of Disk. 

Once we have the website ready we will have to expose the same to the public internet. Though there are multiple ways of exposing the website to the public, below are some of them:

  1. We can expose the website using a load balancer. The load balancer will have a public IP/DNS and the instance where the website is hosted will be private completely making it more secure.
  2. We can further host the static content using a CDN.
  3. Also the straightforward way of hosting the application on a VM and exposing the VM’s public IP using a DNS entry directly. For this exercise, we will be using the method.

Steps

1 – Install MySQL on Ubuntu and complete the secure setup: Follow the below methods to install and set up MySQL on Ubuntu 20.04 and setup to be used securely by WordPress.

  1. Update the package index on your server since this is our first time using apt in this session.
sudo apt update -y
  1. To Install MySQL Server.
sudo apt install mysql-server -y
  1. It is advised that you run a security script that is pre-installed with MySQL after the installation is complete. This script will lock down access to your database system and remove several unsafe default settings. Run the interactive script to get it going: 
sudo mysql_secure_installation

2 – Making a MySQL User and Database for WordPress

WordPress manages and stores user and site data using MySQL. Despite the fact that MySQL is already installed on your computer, let’s make a database and a user for WordPress to use. Log in with the MySQL root (administrative) account to get going. You can access the MySQL administration account using sudo if the auth_socket authentication plugin is set up (which is the default):

To login to the mysql server : sudo mysql

Use the following command instead if you’ve modified the authentication process to need a password for the MySQL root account:

mysql -u root -p

Create a different database that WordPress may access after you are logged in. You can call this whatever you choose, but to keep things straightforward in this guide, we’ll use the word “wordpress.” Input the following to establish a database for WordPress:

CREATE DATABASE wordpress DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci;

Let’s next make a unique MySQL user account that will only be used to manage our new database. From a management and security perspective, it makes sense to create databases and accounts that are only used for one reason. In this article, we’ll use the name wordpressuser; feel free to modify it if you’d prefer.

You will establish an account, choose a password, and allow access to the database you created using the command that comes next. Always pick a strong password here:

CREATE USER 'wordpressuser'@'localhost' IDENTIFIED BY 'password';
GRANT ALL ON wordpress.* TO 'wordpressuser'@'localhost';
exit;

3 – Install Nginx

We will use the high-performance web server Nginx to show web pages to visitors to our website. To acquire this software, we’ll make use of the apt package manage. You can run the apt install to install Nginx:

sudo apt install nginx -y

It is advised that you activate the most stringent profile that permits the traffic you require. You simply need to permit standard HTTP traffic on port 80 since you didn’t establish SSL for your server in this step.

sudo ufw allow 'Nginx HTTP'

Below are two methods to get the server’s public IP:

ip addr show eth0 | grep inet | awk '{ print $2; }' | sed 's/\/.*$//'
curl -4 icanhazip.com

You can now access the nginx server over http://your-server-public-ip

4 – Install PHP

Nginx is set up to serve content, and MySQL is set up to store and handle data. To process code and produce dynamic content for the web server, PHP can now be installed.

Nginx needs an extra application to handle PHP processing and serve as a bridge between the PHP interpreter itself and the web server, whereas Apache embeds the PHP interpreter in each request. Most PHP-based websites can perform better overall thanks to this, although it necessitates additional settings. Install “PHP FastCGI process manager” (php-fpm), and instruct Nginx to send PHP requests to this program for processing. You also require php-mysql, a PHP module that enables communication between PHP and MySQL-based databases. Dependencies for core PHP packages will be installed automatically.

Run the following commands to install php-fpm and php-mysql:

sudo apt install php-fpm php-mysql -y

Along with php we will also have to install additional PHP Extensions for WordPress to work. Below is the command to do so:

sudo apt update -y
sudo apt install php-curl php-gd php-intl php-mbstring php-soap php-xml php-xmlrpc php-zip

Restarting PHP-FPM will enable the active PHP processor to use the newly installed features after the extensions have been installed:

sudo systemctl restart php7.4-fpm

5 – Setting Up Nginx to Utilize the PHP Processor

The Nginx web server allows us to establish server blocks, which are analogous to virtual hosts in Apache and allow us to host several domains on a single server by encapsulating configuration information.

On Ubuntu 20.04, Nginx is set up to serve documents from a directory located at /var/www/html and comes with one server block activated by default. Although this is effective for a single site, managing many sites can be challenging. Instead of making changes to /var/www/html, we’ll construct a directory structure within /var/www for the your_domain website and leave /var/www/html in place to act as the default directory if a client request doesn’t match any other sites.

For your_domain, create the root web directory as follows:

sudo mkdir /var/www/your_domain

After that, change the $USER environment variable to reflect your current system user to assign ownership of the directory:

sudo chown -R $USER:$USER /var/www/your_domain

Use your chosen command-line editor to open a new configuration file in Nginx’s sites-available directory. Here we’ll use “vi”

sudo vi /etc/nginx/sites-available/your_domain

This will produce a brand-new, empty file. Paste the basic configuration shown below:

server {
    listen 80;
    server_name your_domain www.your_domain;
    root /var/www/your_domain;

    index index.html index.htm index.php;

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

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

    location ~ /\.ht {
        deny all;
    }

}

Link to the configuration file from the sites-enabled directory of Nginx to activate your setup:

sudo ln -s /etc/nginx/sites-available/your_domain /etc/nginx/sites-enabled/

The default configuration file should then be delinked from the /sites-enabled/ directory:

sudo unlink /etc/nginx/sites-enabled/default

When Nginx is loaded again later on, this will instruct it to use the configuration. Return to your configuration file and check its contents if any errors are displayed before moving on. By typing, you may check your setup for syntactic issues.

sudo nginx -t

Reload Nginx to implement the modifications when you’re ready:

sudo systemctl reload nginx

Although the web root, /var/www/your_domain, is now live, it is still empty. Create an index.html file there so that we can check to see if your new server block functions as intended:

vi /var/www/your_domain/index.html

Add the following information to this file:

<html>
  <head>
    <title>your_domain website</title>
  </head>
  <body>
    <h1>Hello World!</h1>

    <p>This is the landing page of <strong>your_domain</strong>.</p>
  </body>
</html>

Visit your server’s domain or IP address in your browser by typing it into your server block configuration file’s server_name directive:

http://server_domain_or_IP

6 – Testing PHP with nginx

You should now have a fully operational LEMP stack. You can put it to the test to make sure Nginx can properly transfer.php files to your PHP processor.

Create a test PHP file in your document root to accomplish this. at your text editor, launch a new file called info.php at the document root. And add the following lines should be typed or pasted into the new file. The PHP code below is legitimate and will return details about your server:

vi /var/www/your_domain/info.php
<?php
phpinfo();

The domain name or public IP address you specified in your Nginx configuration file, followed by /info.php, will now take you to this page in your web browser:

http://server_domain_or_IP/info.php

7 – Nginx configuration for WordPress

We will have to edit the existing /etc/nginx/sites-available/your_domain file and add the below lines.

server {
    . . .

    location = /favicon.ico { log_not_found off; access_log off; }
    location = /robots.txt { log_not_found off; access_log off; allow all; }
    location ~* \.(css|gif|ico|jpeg|jpg|js|png)$ {
        expires max;
        log_not_found off;
    }
    . . .
}

Let’s modify the try_files list inside the current location / block. The highlighted line should be added after commenting out the default setting by adding a pound symbol (#) before the line. In this manner, control is transferred to the index.php file with the request arguments rather than sending a 404 error like the default option.

This should resemble something like:

server {
    . . .
    location / {
        #try_files $uri $uri/ =404;
        try_files $uri $uri/ /index.php$is_args$args;
    }
    . . .
}

Save your work and then exit the file.If there were no issues noted, reload Nginx. Let’s now validate the syntax of our settings and reload nginx:

sudo nginx -t
sudo systemctl reload nginx

8 – Downloading and Configuring WordPress

Type the following to download the compressed release after changing into a writable directory:

cd /tmp && curl -LO https://wordpress.org/latest.tar.gz

Extract the downloaded file, rename the sample config file to config file and copy the extracted file to working directory by using following command:

tar xzvf latest.tar.gz && cp /tmp/wordpress/wp-config-sample.php /tmp/wordpress/wp-config.php && sudo cp -a /tmp/wordpress/. /var/www/wordpress

Let’s now make a few modifications to the primary WordPress configuration file.

To add some protection to our installation, you’ll need to alter certain secret keys when you first open the file. WordPress has a safe generator for these values so that you are not need to create them yourself. It won’t hinder usability to have sophisticated, secure values here since these are only used internally.

Type the following to retrieve safe values from the WordPress secret key generator:

curl -s https://api.wordpress.org/secret-key/1.1/salt/

In the output, you will get some secrets. You can set secure keys by pasting these configuration lines straight into your configuration file. Open the WordPress configuration file right now.

sudo vi /var/www/wordpress/wp-config.php

Let’s now change a few of the file’s initial database connection settings. The database name, database user, and associated password that were configured within MySQL will need to be changed.

Setting the way WordPress writes to the filesystem is the other adjustment you ought to make. It is possible to explicitly set the filesystem method to “direct” because you have granted the web server access to write where it is required. If we didn’t set this up with our present settings, WordPress would ask us for our FTP passwords whenever we performed certain operations. Add the following setting somewhere in the file, preferably below the database connection settings:

. . .

define( 'DB_NAME', 'wordpress' );

/** MySQL database username */
define( 'DB_USER', 'wordpressuser' );

/** MySQL database password */
define( 'DB_PASSWORD', 'password' );

. . .

define( 'FS_METHOD', 'direct' );

The server setting is now complete, and you can use WordPress’ web interface to complete the installation. Go to the public IP address or domain name of your server in your web browser.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top