How to Install WordPress with Nginx on Ubuntu 20.04 LTS

Advertisement

WordPress is the most dominant content management system written in PHP, combined with MySQL or MariaDB database. You can create and maintain a site without prior web development or coding knowledge. The first version of WordPress was created in 2003 by Matt Mullenweg and Mike Little and is now used by 70% of the known web market, according to W3Tech. WordPress comes in two versions: the free open source WordPress.org and WordPress.com, a paid service that starts at $5 per month up to $59. Using this content management system is easy and often seen as a stepping stone for making a blog or similar featured site.

In the following tutorial, you will learn how to install self-hosted WordPress using the Nginx, MariaDB, and PHP versions available on Ubuntu 20.04 LTS Focal Fossa, which can be installed on a desktop or but mostly CMS stacks such as this are installed on headless servers such as Ubuntu server. The tutorial will cover some essential points. Further reading into securing your WordPress site and customizing the back-end/front end will be required, and no Linux tutorial can cover this in one hit.

Update Ubuntu

First, begin by running the standard update command to ensure your system is up-to-date to avoid any conflicts during the installation. Hopefully, this is essential, given it is a large installation.

sudo apt update && sudo apt upgrade -y

Install Required Packages

For the most part, most of these packages may already be installed on your server; however, re-run the command to be safe. The packages are very common; you are not installing anything unordinary.

sudo apt install curl git wget unzip -y

Install Latest Nginx – (LEMP Stack)

To kickstart the LEMP stack installation, you will need to install the Nginx web server. A method is to install the latest Nginx mainline or stable from the Ondřej Surý repository to have the most updated software.

Advertisement

To use the latest version of either Nginx mainline or stable, you will need first to import the repository by adding the PPA.

Option 1 – Import mainline repository

Advertisement
sudo add-apt-repository ppa:ondrej/nginx-mainline -y

Option 2 – Import stable repository

sudo add-apt-repository ppa:ondrej/nginx -y

Update your repository to reflect the new change:

sudo apt update

Now that you have installed the Nginx repository and updated the repository list, install Nginx with the following:

sudo apt install nginx-core nginx-common nginx nginx-full

Now check to ensure the latest Nginx from the Ondřej Surý repository was installed using the apt-cache policy command.

Advertisement

apt-cache policy nginx

Example output for Nginx Mainline:

How to Install WordPress with LEMP Stack on Ubuntu 20.04

Note that you may be prompted to keep or replace your existing /etc/nginx/nginx.conf configuration file during the installation. It is recommended to keep your current configuration file by pressing (n).

Installing Nginx with the custom repository comes with additional modules compiled, one of the most sorts after and recommended modules to enable is the Brotli module.

Enable the brotli module by opening your nginx.conf configuration file:

Advertisement
nano /etc/nginx/nginx.conf

Now add the additional lines before in the HTTP{} section:

brotli on;
brotli_comp_level 6;
brotli_static on;
brotli_types application/atom+xml application/javascript application/json application/rss+xml
   application/vnd.ms-fontobject application/x-font-opentype application/x-font-truetype
   application/x-font-ttf application/x-javascript application/xhtml+xml application/xml
   font/eot font/opentype font/otf font/truetype image/svg+xml image/vnd.microsoft.icon
   image/x-icon image/x-win-bitmap text/css text/javascript text/plain text/xml;

The brotli_comp_level can be set between 1 (lowest) and 11 (highest). Typically, most servers sit in the middle, but set it to 11 and monitor CPU usage levels if your server is a monster.

Advertisement

Next, test to make sure the changes are working correctly before making it live:

sudo nginx -t

If the changes are working correctly, you should see the following:

nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful

Now make the changes live by restarting your server:

sudo systemctl restart nginx

Next, enable Nginx on system boot:

sudo systemctl enable nginx --now

Lastly, verify Nginx is running correctly by checking the status.

systemctl status nginx

Example output:

Advertisement
Advertisement

How to Install WordPress with LEMP Stack on Ubuntu 20.04

Configure UFW Firewall for Nginx

Debian users who have installed UFW will need to adjust the UFW rules to allow outside access to the default web ports. Luckily, during the installation, Nginx registers itself with UFW to provide a few profiles that can be used to enable or disable access, making it easy and quick to configure.

By default, UFW should be installed but re-run the installation command if you are unsure.

sudo apt install ufw -y

Next, enable UFW. When you enable the firewall, it will deny all incoming and allow all outgoing by default.

sudo ufw enable

First, list the application profiles to see the Nginx profiles that are available by the following command:

sudo ufw app list

From the output above, you have three profile options to choose from. To break it down, Nginx runs on port 80 (HTTP), Nginx Secure runs on port 443 (HTTPS), and Nginx Full is a combination of allowing both. The most common is either Nginx Full or Nginx Secure.

The tutorial will set up SSL later as nearly all users will be using this; the best choice is to allow both.

Advertisement

sudo ufw allow 'Nginx Full'

Install Latest MariaDB – (LEMP Stack)

The tutorial will recommend installing MariaDB constantly over MySQL due to performance more than anything else.

First, import the official MariaDB repository, 10.5 or 10.6. For those that do not mind upgrading your database, install the latest minor version. The lifetime status can be found here.

Advertisement

Option 1 – Import MariaDB 10.5 (LTS Version Release):

curl -LsS https://downloads.mariadb.com/MariaDB/mariadb_repo_setup | sudo bash -s -- --mariadb-server-version=10.5

Option 2 – Import MariaDB 10.6 (LTS Version Release):

curl -LsS https://downloads.mariadb.com/MariaDB/mariadb_repo_setup | sudo bash -s -- --mariadb-server-version=10.6

Option 3 – Import MariaDB 10.7 (Minor Version Release):

curl -LsS https://downloads.mariadb.com/MariaDB/mariadb_repo_setup | sudo bash -s -- --mariadb-server-version=10.7

Option 4 – Import MariaDB 10.8 (Minor Version Release):

Advertisement

curl -LsS https://downloads.mariadb.com/MariaDB/mariadb_repo_setup | sudo bash -s -- --mariadb-server-version=10.8

Once you have picked a version, update your APT repository.

sudo apt update

Install MariaDB

To install MariaDB, you will need to install the client and the server packages. This can be done as follows:

sudo apt install mariadb-server mariadb-client -y

Confirm the installation of MariaDB by checking the version and build:

mariadb --version

Example output:

Advertisement
mariadb  Ver 15.1 Distrib 10.7.1-MariaDB, for debian-linux-gnu (x86_64) using readline EditLine wrapper

Remember, this is just an example. You can easily change the MariaDB as described at the start of the section.

Check MariaDB server status

Now you have installed MariaDB, and you can verify the status of the database software by using the following systemctl command:

Advertisement

systemctl status mariadb

By default, MariaDB should be enabled. If not, use the following command to activate the service.

sudo systemctl enable mariadb --now

Now recheck the status, and you should get the following:

How to Install WordPress with LEMP Stack on Ubuntu 20.04

Next are some basic systemd commands to control and maintain the MariaDB service.

Stop MariaDB:

sudo systemctl stop mariadb

Enable MariaDB on system startup:

sudo systemctl enable mariadb

Disable MariaDB on system startup:

Advertisement
Advertisement

sudo systemctl disable mariadb

Restart the MariaDB service:

sudo systemctl restart mariadb

Secure MariaDB with Security Script

Next, you will be given a prompt asking you to enter your (MariaDB root password). For now, press the (ENTER) key as the root password is not set yet as below:

sudo mysql_secure_installation

Next, type (Y) and press enter to set up the (root) password as below:

For the next series of questions, you can safely hit (ENTER), which will answer (Y) to all the subsequent questions which ask you to (remove anonymous users, disable remote root login, and remove the test database).

Note the (Y) is capitalized, meaning it is the default answer when you press the (ENTER) key.

Example rundown below:

Advertisement

[joshua@ubuntu-20.04~]$ sudo mariadb-secure-installation

NOTE: RUNNING ALL PARTS OF THIS SCRIPT IS RECOMMENDED FOR ALL MariaDB
      SERVERS IN PRODUCTION USE!  PLEASE READ EACH STEP CAREFULLY!

In order to log into MariaDB to secure it, we'll need the current
password for the root user. If you've just installed MariaDB, and
haven't set the root password yet, you should just press enter here.

Enter current password for root (enter for none): 
OK, successfully used password, moving on...

Setting the root password or using the unix_socket ensures that nobody
can log into the MariaDB root user without the proper authorisation.

You already have your root account protected, so you can safely answer 'n'.

Switch to unix_socket authentication [Y/n] Y <---- Type Y then press the ENTER KEY.
Enabled successfully!
Reloading privilege tables..
 ... Success!


You already have your root account protected, so you can safely answer 'n'.

Change the root password? [Y/n] Y <---- Type Y then press the ENTER KEY.
New password: 
Re-enter new password: 
Password updated successfully!
Reloading privilege tables..
 ... Success!


By default, a MariaDB installation has an anonymous user, allowing anyone
to log into MariaDB without having to have a user account created for
them.  This is intended only for testing, and to make the installation
go a bit smoother.  You should remove them before moving into a
production environment.

Remove anonymous users? [Y/n] Y <---- Type Y then press the ENTER KEY.
 ... Success!

Normally, root should only be allowed to connect from 'localhost'.  This
ensures that someone cannot guess at the root password from the network.

Disallow root login remotely? [Y/n] Y <---- Type Y then press the ENTER KEY.
 ... Success!

By default, MariaDB comes with a database named 'test' that anyone can
access.  This is also intended only for testing, and should be removed
before moving into a production environment.

Remove test database and access to it? [Y/n] Y <---- Type Y then press the ENTER KEY.
 - Dropping test database...
 ... Success!
 - Removing privileges on test database...
 ... Success!

Reloading the privilege tables will ensure that all changes made so far
will take effect immediately.

Reload privilege tables now? [Y/n] Y <---- Type Y then press the ENTER KEY.
 ... Success!

Cleaning up...

All done!  If you've completed all of the above steps, your MariaDB
installation should now be secure.

Thanks for using MariaDB!

Overview of what should have been done above:

  • Setting the password for root accounts.
  • Removing root accounts that are accessible from outside the localhost.
  • Removing anonymous-user accounts.
  • Removing the test database, which anonymous users can access by default.

This step is essential for MariaDB database security and should not be altered or skipped unless you know what you are doing.

Advertisement

Install PHP (LEMP STACK)

The last part of the tutorial will be to install PHP, which is the backend that communicates between Nginx and MariaDB, the middle man. PHP 8.0 is becoming relatively stable, and the newer versions of PHP 8.1 are now available.

The tutorial will focus on importing Ondřej Surý’s latest PHP version, the maintainer for Debian PHP. This is always up to date even when new PHP versions are dropped.

Import PHP PPA

The first step is to import the PPA.

sudo add-apt-repository ppa:ondrej/php -y

Note, you may need to install these dependencies if you have trouble:

Advertisement

sudo apt install apt-transport-https lsb-release ca-certificates software-properties-common -y

Next, update the repository list as the new repository will require some existing packages to be upgraded and is advised to do before installing any versions of PHP.

sudo apt update && sudo apt upgrade

Install PHP-FPM

To install the PHP-FPM, enter the following command.

PHP 8.0:

sudo apt install php8.0-fpm php8.0-cli php8.0-common php8.0-mbstring php8.0-xmlrpc php8.0-soap php8.0-gd php8.0-xml php8.0-intl php8.0-mysql php8.0-cli php8.0-ldap php8.0-zip php8.0-mcrypt php8.0-curl php8.0-opcache php8.0-readline php8.0-xml php8.0-gd -y

PHP 8.1:

Advertisement
sudo apt install php8.1-fpm php8.1-cli php8.1-common php8.1-mbstring php8.1-xmlrpc php8.1-soap php8.1-gd php8.1-xml php8.1-intl php8.1-mysql php8.1-cli php8.1-ldap php8.1-zip php8.1-mcrypt php8.1-curl php8.1-opcache php8.1-readline php8.1-xml php8.1-gd -y

Next, confirm the installed version to check if the installation was successful using the following command.

php --version

Example output:

Advertisement

How to Install WordPress with LEMP Stack on Ubuntu 20.04

Lastly, check the status of the PHP-FPM service to make sure it is running without any errors.

systemctl status php{version}-fpm

Example with PHP-FPM 8.1:

systemctl status php8.1-fpm

Example output:

How to Install WordPress with LEMP Stack on Ubuntu 20.04

By default, when installed, the service is activated on Ubuntu. If the service has not been activated for some reason, use the following command below, then re-check the status.

sudo systemctl php{version}-fpm enable --now

Install WordPress Backend

Download WordPress

Visit the WordPress.org download page and find the latest.zip download link. Then using the wget command, download the file.

wget https://wordpress.org/latest.zip

Create Folder Structure for WordPress

Now you have the archive downloaded, proceed to unzip it and move it to your www directory.

Advertisement
Advertisement

Create the directory for WordPress:

sudo mkdir -p /var/www/html/wordpress

Unzip WordPress to the www directory:

sudo unzip latest.zip -d /var/www/html/

You must set the directory owner permissions to WWW or have trouble with WordPress write permissions.

Set chown permission (important):

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

Set chmod permission folders (important):

sudo find /var/www/html/wordpress -type d -exec chmod 755 {} \;

Set chmod permission files (important):

Advertisement

sudo find /var/www/html/wordpress -type f -exec chmod 644 {} \;

Create Database for WordPress

WordPress requires a database to run hence why you had to install MariaDB. Before continuing further, you need to create a database for WordPress using MariaDB. First, bring up the terminal console and type the following.

Bring up MariaDB shell as root:

Advertisement
sudo mariadb -u root

Next, create the database. This can be any name you want. For the guide, you will name it “WORDPRESSDB.”

Create WordPress database:

CREATE DATABASE WORDPRESSDB;

After the database has been created, you should create a new WordPress site user.

This is done as a security measure, so every database has a different user. If one username is compromised, the attacker doesn’t access all the other website’s databases.

Advertisement

Create the WordPress database user:

CREATE USER 'WPUSER'@localhost IDENTIFIED BY 'PASSWORD';

Replace WPUSER and PASSWORD with whatever username or password you desire.

Do not copy and paste the default user/pass above for security purposes.

Now assign the newly created user access to the WordPress website database only below.

Advertisement

Assign the database to the created WordPress user account:

GRANT ALL PRIVILEGES ON WORDPRESSDB.* TO WPUSER@localhost IDENTIFIED BY 'PASSWORD';

With all database configuration settings complete, you need to flush the privileges to take effect and exit.

Advertisement

Flush Privileges:

FLUSH PRIVILEGES;

Exit MariaDB:

EXIT;

Set WordPress Configuration Files

You need to set some settings in the wp-config-sample.php file. Below, you will see how to rename the sample file and enter the required information.

First, rename the configuration file.

Go to the WordPress directory:

cd /var/www/html/wordpress/

Rename configuration file:

Advertisement
Advertisement

sudo mv wp-config-sample.php wp-config.php

Using a text editor, bring up the newly renamed wp-config.php file. In our example, we will use nano.

sudo nano wp-config.php

Next, you will enter the database name, user account with a password, and host IP address if different than localhost.

// ** MySQL settings - You can get this info from your web host ** //
/** The name of the database for WordPress */ 

define( 'DB_NAME', 'WORDPRESSDB' );                 <--------------- change this

/* MySQL database username */ 

define( 'DB_USER', 'WPUSER );                               <--------------- change this

/* MySQL database password */

define( 'DB_PASSWORD', 'PASSWORD' );             <--------------- change this

/* MySQL hostname, change the IP here if external DB set up */ 

define( 'DB_HOST', 'localhost' );

/* Database Charset to use in creating database tables. */

define( 'DB_CHARSET', 'utf8' );

/* The Database Collate type. Don't change this if in doubt. */

define( 'DB_COLLATE', '' );

While you are in this file, adding extra settings will make your WordPress easier to manage, such as direct file saving instead of using FTP and increased memory size limits.

##Save files direct method##
define( 'FS_METHOD', 'direct' );

##Increase memory limit, 256MB is recommended##
define('WP_MEMORY_LIMIT', '256M');

##change Wordpress database table prefix if wanted##
$table_prefix = 'wp_';

Set WordPress Security Salt Keys

It would be best to visit WordPress secret-key API to generate your own. The address salt key generator can be found at https://api.wordpress.org/secret-key/1.1/salt/. Replace the example lines with the codes from the generator.

DO NOT COPY THE EXAMPLE BELOW, AND IT’S JUST FOR REFERENCE.

define('AUTH_KEY',         '<3yfS7/>%m.Tl^8Wx-Y8-|T77WRK[p>(PtH6V]Dl69^<8|K86[_Z},+THZ25+nJG');
define('SECURE_AUTH_KEY',  'bN#Qy#ChBX#Y`PE/_0N42zxgLD|5XpU[mu.n&:t4q~hg<UP/b8+xFTly_b}f]M;!');
define('LOGGED_IN_KEY',    'owpvIO-+WLG|,1)CQl*%gP1uDp}s(jUbYQ[Wm){O(x@sJ#T}tOTP&UOfk|wYsj5$');
define('NONCE_KEY',        '8=Vh|V{D<>`CLoP0$H!Z3gEqf@])){L+6eGi`GAjV(Mu0YULL@sagx&cgb.QVCbi');
define('AUTH_SALT',        '%TX*X$GE-;|?<-^(+K1Un!_Y<hk-Ne2;&{c[-v!{q4&OiJjQon /SHcc/:MB}y#(');
define('SECURE_AUTH_SALT', '=zkDT_%}J4ivjjN+F}:A+s6e64[^uQ<qNO]TfHS>G0elz2B~7Nk.vRcL00cJoo7*');
define('LOGGED_IN_SALT',   '{$-o_ull4|qQ?f=8vP>Vvq8~v>g(2w12`h65ztPM(xo!Fr()5xrqy^k[E~TwI!xn');
define('NONCE_SALT',       'a1G(Q|X`eX$p%6>K:Cba!]/5MAqX+L<A4yU_&CI)*w+#ZB+*yK*u-|]X_9V;:++6');

Nginx Server Block Configuration

Now, you are almost ready to install WordPress through the web UI. However, you need to configure your Nginx server block. The settings below are pretty crucial. It should be noted to emphasize the importance of “try_files $uri $uri/ /index.php?$args;” as it is often an issue with other tutorials that leave the ending ?$args left out, giving you major site health issues comes to the REST API of WordPress.

Advertisement

First, create a new server configuration file with the following command replacing the example with your domain name,

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

Below is an example; you can choose the parts; however, the “location ~ \.php$” needs to be in the Nginx configuration file.

Advertisement

NOTE: Make sure to change www.example.com and example.com and the root path.

server {

  listen 80;
  listen [::]:80;
  server_name www.example.com example.com;

  root /var/www/html/wordpress;

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


  location / {
  try_files $uri $uri/ /index.php?$args;
 }

  location ~* /wp-sitemap.*\.xml {
    try_files $uri $uri/ /index.php$is_args$args;
  }

  client_max_body_size 100M;

  location ~ \.php$ {
    fastcgi_pass unix:/run/php/php8.1-fpm.sock;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    include fastcgi_params;
    include snippets/fastcgi-php.conf;
    fastcgi_buffer_size 128k;
    fastcgi_buffers 4 128k;
    fastcgi_intercept_errors on;	
  }

 gzip on; 
 gzip_comp_level 6;
 gzip_min_length 1000;
 gzip_proxied any;
 gzip_disable "msie6";
 gzip_types
     application/atom+xml
     application/geo+json
     application/javascript
     application/x-javascript
     application/json
     application/ld+json
     application/manifest+json
     application/rdf+xml
     application/rss+xml
     application/xhtml+xml
     application/xml
     font/eot
     font/otf
     font/ttf
     image/svg+xml
     text/css
     text/javascript
     text/plain
     text/xml;

  # assets, media
  location ~* \.(?:css(\.map)?|js(\.map)?|jpe?g|png|gif|ico|cur|heic|webp|tiff?|mp3|m4a|aac|ogg|midi?|wav|mp4|mov|webm|mpe?g|avi|ogv|flv|wmv)$ {
      expires    90d;
      access_log off;
  }
  
  # svg, fonts
  location ~* \.(?:svgz?|ttf|ttc|otf|eot|woff2?)$ {
      add_header Access-Control-Allow-Origin "*";
      expires    90d;
      access_log off;
  }

  location ~ /\.ht {
      access_log off;
      log_not_found off;
      deny all;
  }
}

Note, find and replace the above line “fastcgi_pass unix:/run/php/php8.1-fpm.sock;” to “fastcgi_pass unix:/run/php/php8.0-fpm.sock;” for 8.0.

Next, you will need to enable the Nginx configuration file from “sites-available.” To do this, you will create a symlink to “sites-enabled” as follows.

sudo ln -s /etc/nginx/sites-available/example.com.conf /etc/nginx/sites-enabled/

Make sure to replace “example.conf” with your configuration file name.

Advertisement

You can now do a dry run and then restart your Nginx server if everything is ok.

sudo nginx -t

After checking that everything is ok with your Nginx dry run test, restart the Nginx service.

sudo systemctl restart nginx

PHP.ini Configuration

Before moving onto the web UI installation part, you should adjust your PHP for optimal use for WordPress. These settings are more of a guide, and you can increase or decrease them as you see fit.

First, bring up your php.ini. Note that your location may differ depending on your PHP version number.

Advertisement

PHP 8.0 Example:

sudo nano /etc/php/8.0/fpm/php.ini

PHP 8.1 Example:

Advertisement

sudo nano /etc/php/8.1/fpm/php.ini

WordPress media files can be pretty significant, and the default can be too low. You can increase this to roughly what you think your most extensive file size will be.

Please find the following lines below and adjust them to your needs.

##increase upload max size recommend 50 to 100mb## 
 upload_max_filesize = 100MB

##increase post max size recommend 50 to 100mb##
 post_max_size = 100MB

## increase max execution time recommend 150 to 300##
 max_execution_time = 300

## increase GET/POST/COOKIE input variables recommend 5000 to 10000##
max_input_vars = 5000

## increase memory limit recommend 256mb or 512mb## MAKE SURE THIS MATCHES THE MB SETTING IN YOUR WP-CONFIG.CONF / ENSURE YOUR SYSTEM HAS ENOUGH RAM BEFORE RAISING!!!!
memory_limit = 256M

Now restart your PHP-FPM server.

PHP 8.0 Example:

sudo systemctl restart php8.0-fpm

PHP 8.1 Example:

sudo systemctl restart php8.1-fpm

The PHP settings you adjusted are for the PHP backend. You will also need to change the Nginx server block to allow large body sizes. This is done by re-opening your server block and adding the following line.

Advertisement
Advertisement

Open up your server block.

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

Adjust this line to increase body size.

client_max_body_size 100M;

Remember, keep the client max size the same as your max size PHP file setting.

Next, test the changes, then restart your Nginx server if everything is ok.

sudo nginx -t

After checking that everything is ok with your Nginx dry run test, restart the Nginx service.

sudo systemctl restart nginx

Install WordPress Frontend

Now that all the backend setup and configuration are complete, you can go to your domain and begin installing.

Advertisement

##go to installation address##
 https://www.yoursite.com
##alternative url##
 https://www.yoursite.com/wp-admin/install.php

The first page you arrive too will be the front-end installation wizard.

Example:

Advertisement
How to Install WordPress with Nginx on Ubuntu 20.04 LTS

Select your language, then click Continue.

On the next screen, you can enter your site title, username, password, and email of the main admin associated with the WordPress site. For now, make sure to set a strong password and a working e-mail; all other settings can be adjusted later on in the settings panel of WordPress.

Example:

How to Install WordPress with Nginx on Ubuntu 20.04 LTS

If you are building a website, enabling “strongly discourage search engines from indexing” prevents Google or Bing or any other “good/reputable search engine bot” from indexing a WIP website.

Advertisement

Once finished, click Install WordPress on the bottom of the screen.

Next, if successful, you should arrive at the following screen informing you to log in.

Example:

How to Install WordPress with Nginx on Ubuntu 20.04 LTS

Next, log in as follows.

Advertisement

Example:

How to Install WordPress with Nginx on Ubuntu 20.04 LTS

Once logged in, you should arrive at your dashboard; from here, you can begin to build or import your website.

Advertisement

Example:

How to Install WordPress with Nginx on Ubuntu 20.04 LTS

Congratulations, you have successfully installed the latest version of WordPress on Nginx with the LEMP stack.

Secure Nginx with Let’s Encrypt SSL Free Certificate

Ideally, you would want to run your Nginx on HTTPS using an SSL certificate. The best way to do this is to use Let’s Encrypt, a free, automated, and open certificate authority run by the nonprofit Internet Security Research Group (ISRG).

First, install the certbot package as follows.

sudo apt install python3-certbot-nginx -y

Once installed, run the following command to start the creation of your certificate:

sudo certbot --nginx --agree-tos --redirect --hsts --staple-ocsp --email you@example.com -d www.example.com

This ideal setup includes force HTTPS 301 redirects, a Strict-Transport-Security header, and OCSP Stapling. Just make sure to adjust the e-mail and domain name to your requirements.

Advertisement
Advertisement

Now your URL will be HTTPS://www.example.com instead of HTTP://www.example.com.

If you use the old HTTP URL, it will automatically redirect to HTTPS.

Optionally, you can set a cron job to renew the certificates automatically. Certbot offers a script that does this automatically, and you can first test to make sure everything is working by performing a dry run.

sudo certbot renew --dry-run

If everything is working, open your crontab window using the following terminal command.

sudo crontab -e

Next, please specify the time when it should auto-renew. This should be checked daily at a minimum, and if the certificate needs to be renewed, the script will not update the certificate. Use the crontab.guru if you need help finding a good time, the calculator is terrific, especially for new users. I highly recommend using this site.

00 00 */1 * * /usr/sbin/certbot-auto renew

Session Saving Errors

Sometimes, you may see your plugins give you an error saving session, and this can happen if the user permissions are out of whack in the /var/lib/php/sessions location.

Advertisement

This can be fixed using the following command.

sudo chown -R www-data:www-data /var/lib/php/sessions/

As above, you set the www-data user and group to the owner of the sessions, and this should give WordPress the ability to write session information into the directory. These are for such plugins that automate tasks like social media posting.

Advertisement

Remember, if anything goes wrong, restore the backup.

sudo cp /etc/php/8.1/fpm/backup-php.ini /etc/php/8.1/fpm/php.ini

Comments and Conclusion

WordPress offers a fantastic ability to create quick websites with templates and plugins, and the plugin store hosts a tremendous amount of options. However, to unlock the full potential of most themes and add-ons, they are all paywall, but most are affordable.

Self-hosting WordPress is quite a bit of fun. However, making sure you keep up with security and updating is essential. WordPress is the most targetted CMS on earth by attackers, and your site will, in its first day without even being listed, be scanned for exploits, and brute force attempts will begin.

Share on: