How to Install WordPress with Nginx

|

Nginx is a very powerful web-server, WordPress runs very efficiently on Nginx. If you’re looking to host your WordPress blog on Nginx server this guide will help you from setting up a server to Post-Install Maintenance to your WordPress website on Nginx.

Let’s start with setting up a server, for this guide, I’m using Ubuntu 18.10 latest stable version. It doesn’t matter which Cloud host you choose as long as they allow you to install Linux, Ubuntu or any Linux family OS this guide will work , for here demonstration I’m using Ubuntu 18.04 at the end of the guide I will provide you detail how to automatic security updates for your OS that will automatically updates all security patches.

The first step in order to install WordPress with Nginx in ubuntu is once you have Server up and running try logging in with your server. here I’m using digital Ocean.

ssh [email protected]_server_ip

Once you login into your Server We will perform step by Step operation to install Nginx, MySQL, PHP, and WordPress.

Step 1 : Setup Basic Firewall

you need to make sure that firewalls allow SSH connection.

sudo ufw allow OpenSSH

Afterward, we can enable the firewall by typing:

sudo ufw enable

Type Y and hit the ENTER key to proceed. You can see that SSH connections are still allowed by typing:

sudo ufw status
Check Your Firewall Status on Ubuntu

Step 2 : Installing the Nginx Web Server

We will use Ubuntu’s default apt package to complete the necessary installations.

sudo apt update
sudo apt install nginx

You will only need to allow Nginx traffic on port 80, In Step 1 we enabled basic firewall

sudo ufw allow 'Nginx HTTP'

You can verify the change by running.

sudo ufw status

This command’s output will show that HTTP traffic is allowed.

After HTTPS traffic allowed in Firewall

Now If you go http://server_domain_or_IP you will see below page, you have successfully installed Nginx.

Nginx Welcome Screen

Step 3 : Installing MySQL to Manage Site Data

Install MySQL by typing.

sudo apt install mysql-server

To secure the installation, Initiate the script by typing.

sudo mysql_secure_installation

This script will ask if you want to configure the VALIDATE PASSWORD PLUGIN. If you enable then, password that does not match to the criteria that will be rejected MySQL with an error. ( you should always set a strong MySQL password.)

Answer Y for yes, or anything else to continue without enabling.

MySQL Secure Installation password Setup

Next, you’ll be asked to submit and confirm a root password. For the rest of the questions, you should press Y and hit the ENTER key at each prompt. 

Now mySQL is installed

Let’s create a Database for WordPress.

Enter into MySQL by typing just mysql

Enter into Mysql after installing on Ubuntu

First create database by typing, I have given my database name as wordpress

CREATE DATABASE wordpress DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci;

Next, we are going to create a separate MySQL user account that we will use exclusively to operate on our new database.

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

Now, We need to flush the privileges so that the current instance of MySQL knows about the recent changes we’ve made

FLUSH PRIVILEGES;

Exit out of MySQL by typing:

exit;

Step 4 : Installing PHP

We need to install some of the most popular PHP extensions for use with WordPress by typing:

sudo apt install php-curl php-gd php-intl php-mbstring php-soap php-xml php-xmlrpc php-zip php-fpm php-mysql php-bcmath php-imagick

When you are finished installing the extensions, restart the PHP-FPM process. Here we installed latest PHP version to check your PHP version type php -v in a terminal

sudo systemctl restart php7.2-fpm

Step 5 : Configuring Nginx

Now We need to configure Nginx file to serve WordPress for that We will create Nginx file first

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

Add the following code in this file and change the server_name to your domain name

server {
        listen 80;
        root /var/www/wordpress;
        index index.php index.html index.htm index.nginx-debian.html;
        server_name myexampleblog.com www.myexampleblog.com;  #change this to your domain name here

        location / {
                try_files $uri $uri/ /index.php$is_args$args;
        }
        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;
        }
        location ~ \.php$ {
                include snippets/fastcgi-php.conf;
                fastcgi_pass unix:/var/run/php/php7.2-fpm.sock;
        }

        location ~ /\.ht {
                deny all;
        }
}

After adding this content, save and close the file.

Enable your new server block by creating a symbolic link from your new server block configuration file (in the /etc/nginx/sites-available/ directory) to the /etc/nginx/sites-enabled/ directory by following code:

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

Then, unlink the default configuration file from the /sites-enabled/ directory:

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

Now, we can check our configuration for syntax errors by typing:

sudo nginx -t

If no configuration error, reload Nginx by typing:

sudo systemctl reload nginx

That’s all you needed to configure Nginx, Make sure you have changed the server_name in the configuration file.

Step 6 : Downloading WordPress

Now, we will download the latest WordPress by typing following code( here I’m creating new directory tmp to download WordPress

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

Extract the compressed file to create the WordPress directory structure

tar xzvf latest.tar.gz

Now, we can copy the entire contents of the directory into our document root. ( we’re copying everything into /var/www/wordpres/ directory because we have added root /var/www/wordpress/ as to serve WordPress from that directory in the Nginx config file)

sudo cp -a /tmp/wordpress/. /var/www/wordpress

Now that our files are in place, we’ll assign ownership them to the www-data user and group

sudo chown -R www-data:www-data /var/www/wordpress

Now, we can copy over the sample configuration file to wp-config.php

sudo cp /var/www/wordpress/wp-config-sample.php /var/www/wordpress/wp-config.php

Now the last part is editing wp-config.php

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

Find the section that contains the dummy values for those settings. It will look something like this. (we need to replace this dummy values)

define( 'AUTH_KEY',         'put your unique phrase here' );
define( 'SECURE_AUTH_KEY',  'put your unique phrase here' );
define( 'LOGGED_IN_KEY',    'put your unique phrase here' );
define( 'NONCE_KEY',        'put your unique phrase here' );
define( 'AUTH_SALT',        'put your unique phrase here' );
define( 'SECURE_AUTH_SALT', 'put your unique phrase here' );
define( 'LOGGED_IN_SALT',   'put your unique phrase here' );
define( 'NONCE_SALT',       'put your unique phrase here' );

Delete these line and paste value from this WordPress URL https://api.wordpress.org/secret-key/1.1/salt/

Next, we need to modify some of the database connection settings at the beginning of the file. and we need to add one line define(‘FS_METHOD’, ‘direct’).

. . .

define('DB_NAME', 'wordpress');

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

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

. . .

define('FS_METHOD', 'direct');

Now Save this file and go to your server Ip Address

http://server_domain_or_IP

BOOM !

WordPress Installation Screen After Setup

Your WordPress installation is loading, Now you can set up your admin account from here, select your language and Next, you will come to the main setup page.

WordPress Username and Password setup on Ubuntu

Select a name for your WordPress site and choose a username (it is recommended not to choose something like “admin” for security purposes).

A strong password is generated automatically. Save this password or select an alternative strong password. When you click install WordPress, you will be taken to a page that prompts you to log in

Bonus – Attach server to domain and install Free SSL certificat

As we already added the server_name name in our Nginx config file. Now we need to setup DNS to point our server’s IP to a domain.

You need to add DNS A record as shown in below image. Go to your domain registrar and you can add A records points to the server IP address.

Change DNS to WordPress Server in CloudFront

After adding DNS record, change the WordPress URL to your domain name.

Change WordPress URL after installing on Ubuntu

After saving this you will be logged out once you logged back in you will the URL is changed.

WordPress URL Changed after Site Address change

Now you have attached domain to your wordpress installation let’s begin to install SSL certificate.

We will use Let’s Encrypt to obtain an SSL certificate. Let’s Encrypt is a freeautomated, and open Certificate Authority backed by major tech organization.

We’ll use certbot to install SSL certificate, let’s install certbot first.

sudo add-apt-repository ppa:certbot/certbot

You’ll need to press ENTER to accept.

Install Certbot’s Nginx package with apt:

sudo apt install python-certbot-nginx

now, You need to allow  HTTPS traffic Through the Firewall

check your ufw firewall current setting, You can see the current setting by typing:

sudo ufw status

our current status should look like this,


Status: active

To                         Action      From
--                         ------      ----
OpenSSH                    ALLOW       Anywhere                  
Nginx HTTP                 ALLOW       Anywhere                  
OpenSSH (v6)               ALLOW       Anywhere (v6)             
Nginx HTTP (v6)            ALLOW       Anywhere (v6)             

[email protected]:~# 

Now, allow Nginx full profile and delete the Nginx HTTP profile allowance.

sudo ufw allow 'Nginx Full'
sudo ufw delete allow 'Nginx HTTP'

Now check your status it should look like this,

sudo ufw status
[email protected]:~# sudo ufw status
Status: active

To                         Action      From
--                         ------      ----
OpenSSH                    ALLOW       Anywhere                  
Nginx Full                 ALLOW       Anywhere                  
OpenSSH (v6)               ALLOW       Anywhere (v6)             
Nginx Full (v6)            ALLOW       Anywhere (v6)             

[email protected]log:~# 

Now Obtain SSL certificate for your domain,

sudo certbot --nginx -d myexampleblog.com -d www.myexampleblog.com

Certbot will ask you a couple of agreement and redirect from HTTP to HTTPS. ( choose if you want the server to redirect HTTPS). If you see below output then your SSL certificate is successfully installed.

[email protected]:~# sudo certbot --nginx -d myexampleblog.com -d www.myexampleblog.com
Saving debug log to /var/log/letsencrypt/letsencrypt.log
Plugins selected: Authenticator nginx, Installer nginx
Enter email address (used for urgent renewal and security notices) (Enter 'c' to
cancel): [email protected]

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Please read the Terms of Service at
https://letsencrypt.org/documents/LE-SA-v1.2-November-15-2017.pdf. You must
agree in order to register with the ACME server at
https://acme-v02.api.letsencrypt.org/directory
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
(A)gree/(C)ancel: A

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Would you be willing to share your email address with the Electronic Frontier
Foundation, a founding partner of the Let's Encrypt project and the non-profit
organization that develops Certbot? We'd like to send you email about our work
encrypting the web, EFF news, campaigns, and ways to support digital freedom.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
(Y)es/(N)o: Y
Obtaining a new certificate
Performing the following challenges:
http-01 challenge for myexampleblog.com
http-01 challenge for www.myexampleblog.com
Waiting for verification...
Cleaning up challenges
Deploying Certificate to VirtualHost /etc/nginx/sites-enabled/wordpress
Deploying Certificate to VirtualHost /etc/nginx/sites-enabled/wordpress

Please choose whether or not to redirect HTTP traffic to HTTPS, removing HTTP access.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
1: No redirect - Make no further changes to the webserver configuration.
2: Redirect - Make all requests redirect to secure HTTPS access. Choose this for
new sites, or if you're confident your site works on HTTPS. You can undo this
change by editing your web server's configuration.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Select the appropriate number [1-2] then [enter] (press 'c' to cancel): 2
Redirecting all traffic on port 80 to ssl in /etc/nginx/sites-enabled/wordpress
Redirecting all traffic on port 80 to ssl in /etc/nginx/sites-enabled/wordpress

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Congratulations! You have successfully enabled https://myexampleblog.com and
https://www.myexampleblog.com

You should test your configuration at:
https://www.ssllabs.com/ssltest/analyze.html?d=myexampleblog.com
https://www.ssllabs.com/ssltest/analyze.html?d=www.myexampleblog.com
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

IMPORTANT NOTES:
 - Congratulations! Your certificate and chain have been saved at:
   /etc/letsencrypt/live/myexampleblog.com/fullchain.pem
   Your key file has been saved at:
   /etc/letsencrypt/live/myexampleblog.com/privkey.pem
   Your cert will expire on 2019-07-10. To obtain a new or tweaked
   version of this certificate in the future, simply run certbot again
   with the "certonly" option. To non-interactively renew *all* of
   your certificates, run "certbot renew"
 - Your account credentials have been saved in your Certbot
   configuration directory at /etc/letsencrypt. You should make a
   secure backup of this folder now. This configuration directory will
   also contain certificates and private keys obtained by Certbot so
   making regular backups of this folder is ideal.
 - If you like Certbot, please consider supporting our work by:

   Donating to ISRG / Let's Encrypt:   https://letsencrypt.org/donate
   Donating to EFF:                    https://eff.org/donate-le

[email protected]:~# 

One last important thing! Auto-Renewal your SSL certificate type below command

sudo certbot renew --dry-run

you will see below output.

[email protected]:~# sudo certbot renew --dry-run
Saving debug log to /var/log/letsencrypt/letsencrypt.log

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Processing /etc/letsencrypt/renewal/myexampleblog.com.conf
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Cert not due for renewal, but simulating renewal for dry run
Plugins selected: Authenticator nginx, Installer nginx
Renewing an existing certificate
Performing the following challenges:
http-01 challenge for myexampleblog.com
http-01 challenge for www.myexampleblog.com
Waiting for verification...
Cleaning up challenges

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
new certificate deployed with reload of nginx server; fullchain is
/etc/letsencrypt/live/myexampleblog.com/fullchain.pem
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
** DRY RUN: simulating 'certbot renew' close to cert expiry
**          (The test certificates below have not been saved.)

Congratulations, all renewals succeeded. The following certs have been renewed:
  /etc/letsencrypt/live/myexampleblog.com/fullchain.pem (success)
** DRY RUN: simulating 'certbot renew' close to cert expiry
**          (The test certificates above have not been saved.)
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

IMPORTANT NOTES:
 - Your account credentials have been saved in your Certbot
   configuration directory at /etc/letsencrypt. You should make a
   secure backup of this folder now. This configuration directory will
   also contain certificates and private keys obtained by Certbot so
   making regular backups of this folder is ideal.
[email protected]:~# 

Now you have successfully installed SSL and it’s on automatically renewal.

Let’s change WordPress URL to HTTPS.

Change WordPress URL to https

Now IF you go to your WordPress website you will see HTTPS.

Change WordPress URL to https

Post-Install Maintenance

We strongly suggest you turn on automatic security updates for your OS. In Ubuntu use the following command.

sudo dpkg-reconfigure -plow unattended-upgrades

If you are using a password and not an SSH key, be sure to enforce a strong root password.

Help us improve this guide! Feel free to ask about it on Comment.

Leave a Comment

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