Install WordPress on Ubuntu 20.04 with Apache, MariaDB, PHP7.4 (LAMP)

This tutorial is going to show you how to install WordPress on Ubuntu 20.04 with Apache, MariaDB and PHP7.4 (LAMP Stack). WordPress is the most popular CMS (Content Management System) in the world. It is estimated that more than a third of websites today are powered by WordPress. PHP7.4 made into the Ubuntu 20.04 repository and WordPress runs perfectly with it.

Prerequisite

1. To follow this tutorial, you need an Ubuntu 22.04 OS running on a remote server. If you are looking for a virtual private server (VPS), I recommend Kamatera VPS, which features:

  • 30 days free trial.
  • Starts at $4/month (1GB RAM)
  • High-performance KVM-based VPS
  • 9 data centers around the world, including the United States, Canada, UK, Germany, The Netherlands, Hong Kong, and Isreal.

Follow the tutorial linked below to create your Linux VPS server at Kamatera.

2. You also need a domain name, so visitors can type a domain name in the web browser address bar to access your website. I registered my domain name at NameCheap because the price is low and they give whois privacy protection free for life.

3. This tutorial assumes that you have already set up a LAMP stack on Ubuntu 20.04. If not, please check out the following tutorial.

After finishing LAMP installation, come back here and read on.

Step 1: Download WordPress

SSH into your Ubuntu 20.04 server and update existing software.

sudo apt update && sudo apt upgrade

Next, go to wordpress.org download page and download the zip archive. You can acquire the direct download link by right-clicking the download button and select copy link location.

install-wordpress-on-ubuntu-20.04

Then at the command line, type in wget followed by the direct download link to download WordPress to your Ubuntu 20.04 server.

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

Next, extract the archive to the /var/www/ directory with unzip.

sudo apt install unzip

sudo mkdir -p /var/www/

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

The -d option specifies the target directory. WordPress web files will be extracted to /var/www/wordpress. We can rename this directory like below, so it’s easy for us to identify each directory. Replace example.com with your real domain name.

sudo mv /var/www/wordpress /var/www/example.com

Step 2: Create a Database and User for WordPress Site

Log into MariaDB shell as root with the following command.

sudo mariadb -u root

or

sudo mysql -u root

Once you are logged in, create a database for WordPress using the following command. I named it wordpress, but you can use whatever name you like such as your site name. (Don’t leave out the semicolon.)

create database wordpress;

Then enter the command below to create a database user for WordPress. This command also grants all privileges of WordPress database to the user. Replace wpuser and your-password with your preferred username and password.

grant all privileges on wordpress.* to wpuser@localhost identified by 'your-password';

Flush the privileges table for the changes to take effect and then exit out of MariaDB shell.

flush privileges;

exit;

Step 3: Configure WordPress

Go to your WordPress directory.

cd /var/www/example.com/

Copy the sample configuration file and rename it to wp-config.php.

sudo cp wp-config-sample.php wp-config.php

Now edit the new config file with a command-line text editor like Nano.

sudo nano wp-config.php

Find the following lines and replace the red texts with the database name, username and password you created in the previous step.

/** The name of the database for WordPress */
define('DB_NAME', 'database_name_here');

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

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

Save and close the file. To save the file in Nano text editor, press Ctrl+O, then press Enter to confirm. Next, press Ctrl+X to exit.

We also need to set the Apache user (www-data) as the owner of the WordPress site directory using the following command.

sudo chown www-data:www-data /var/www/example.com/ -R

Step 4: Create an Apache Virtual Host file for WordPress

Run the following command to create a virtual host file for your WordPress site in the /etc/apache2/sites-available/ directory.

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

Put the following texts into the file. Replace the red texts with your own domain name. Don’t forget to create A records for your domain name in your DNS manager.

<VirtualHost *:80>       
        ServerName www.example.com
        ServerAlias example.com

        DocumentRoot /var/www/example.com

        #This enables .htaccess file, which is needed for WordPress Permalink to work. 
        <Directory "/var/www/example.com">
             AllowOverride All
        </Directory>

        ErrorLog ${APACHE_LOG_DIR}/example.com.error.log
        CustomLog ${APACHE_LOG_DIR}/example.com.access.log combined
</VirtualHost>

Save and close the file. Then test configurations.

sudo apache2ctl configtest

If you see “Syntax OK”, then enable this virtual host.

sudo a2ensite example.com.conf

And reload Apache for the changes to take effect.

sudo systemctl reload apache2

Set a correct A record for your domain name, then enter your domain name in browser address bar.

example.com

or

example.com/wp-admin/install.php

You shall see the WordPress installation wizard. Select a language.

install-wordpress-ubuntu-17.10

If the installation wizard isn’t displayed, then you probably need to install some PHP7 extensions.

sudo apt install php7.4-mbstring php7.4-xml php7.4-mysql php7.4-common php7.4-gd php7.4-bcmath php7.4-json php7.4-cli php7.4-curl php7.4-zip

Then reload Apache and the wizard should now be displayed.

sudo systemctl reload apache2

Before entering your sensitive information in the setup wizard, it’s recommended to enable HTTPS to prevent traffic hijacking.

Step 5: Enabling HTTPS

To encrypt the HTTP traffic, we can enable HTTPS by installing a free TLS certificate issued from Let’s Encrypt. Run the following command to install Let’s Encrypt client (certbot) on Ubuntu 20.04 server.

sudo apt install certbot python3-certbot-apache

And run this command to obtain and install TLS certificate.

sudo certbot --apache --agree-tos --redirect --hsts --uir --staple-ocsp --email [email protected] -d yourdomain.com,www.yourdomain.com

Wher

  • --apache: Use the Apache plugin.
  • --agree-tos: Agree to terms of service.
  • --redirect: Force HTTPS by 301 redirect.
  • --hsts: Add the Strict-Transport-Security header to every HTTP response. Forcing browser to always use TLS for the domain. Defends against SSL/TLS Stripping.
  • --uir: Add the “Content-Security-Policy: upgrade-insecure-requests” header to every HTTP response.
  • --staple-ocsp: Enables OCSP Stapling. A valid OCSP response is stapled to the certificate that the server offers during TLS.
  • --email: Email used for registration and recovery contact.
  • -d flag is followed by a list of domain names, separated by comma. You can add up to 100 domain names.

The certificate should now be obtained and automatically installed.

wordpress apache https

Now if you reload the WordPress setup wizard, you can see that HTTP is automatically redirected to HTTPS connection.

Step 6: Finish the Installation with the Setup Wizard

Create an admin account and click the Install WordPress button.

wordpress ubuntu 20.04 PHP7.4

And now your new WordPress site is installed.

install wordpress ubuntu 20.04 LAMP

Redirecting WWW to Non-WWW (Or Vice-Versa)

We have already enabled redirecting HTTP to HTTPS, what’s left to do is redirect www to non-www, or vice versa. If you are using WordPress, then it’s very easy. Simply go to WordPress Dashboard > Settings > General and set your preferred version (www or non-www) in WordPress Address and Site Address. Be sure to include the https:// prefix.

letsencrypt apache redirect

Fixing the Double 301 Redirect

We set the preferred domain version in the WordPress Address and Site Address fields. However, there’s a double 301 redirect problem. First, Apache server redirects HTTP to HTTPS, then WordPress redirects to www or non-www domain.

Some may argue that you can lose SEO link juice when doing double 301 redirect. If you are worried about that, then you can use the method below to make all domain versions to go directly to the final destination, so there will be a single 301 redirect.

Edit your virtual host file. (Not the SSL virtual host)

sudo nano /etc/apache2/sites-enabled/example.com.conf

CertBot client added the following lines to the file to redirect HTTP to HTTPS.

RewriteEngine on
RewriteCond %{SERVER_NAME} =example.com [OR]
RewriteCond %{SERVER_NAME} =www.example.com
RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [END,NE,R=permanent]

To redirect to www or non-www domain, you need to change the last line. Replace %{SERVER_NAME} with your preferred domain version like below. (www domain)

RewriteRule ^ https://www.example.com%{REQUEST_URI} [END,NE,R=permanent]

If you prefer non-www domain, change it to the following.

RewriteRule ^ https://example.com%{REQUEST_URI} [END,NE,R=permanent]

Then save and close the file. We will also need to edit the SSL virtual host.

sudo nano /etc/apache2/sites-enabled/example.com-le-ssl.conf

Add the following lines above the closing </VirtualHost> tag to redirect non-www to www domain.

RewriteEngine on
RewriteCond %{SERVER_NAME} =example.com
RewriteRule ^ https://www.example.com%{REQUEST_URI} [END,NE,R=permanent]

If you want to redirect www to non-www domain, add the following lines instead.

RewriteEngine on
RewriteCond %{SERVER_NAME} =www.example.com
RewriteRule ^ https://example.com%{REQUEST_URI} [END,NE,R=permanent]

Save and close the file. Reload Apache service for the changes to take effect.

sudo systemctl reload apache2

To be more clear, below is a screenshot of my Apache virtual host file and SSL virtual host file for redirecting non-www to www domain.

wordpress apache www or non-www

Apache Virtual Host File

wordpress apache www or non-www redirect https

Apache SSL Virtual Host File

Make sure you set your preferred domain version in WoredPress Address and Site Address before editing Apache virtual host files. If WordPress settings contradict with Apache configuration, your site will end up in a redirect loop.

TLS Certificate Auto-Renewal

To automatically renew Let’s Encrypt certificate, simply edit root user’s crontab file.

sudo crontab -e

Then add the following line at the bottom.

@daily certbot renew --quiet && systemctl reload apache2

Reloading Apache is needed for it to present the new certificate to clients.

Increase Upload File Size Limit

If you use the Apache PHP module to run PHP script, then there’s no upload file size limit. If you use PHP-FPM to run PHP script, change the file size limit so you can upload big files to the WordPress media library. The default maximum file size for uploading in PHP-FPM is 2MB. To increase the upload size limit, edit the PHP configuration file.

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

Find the following line (line 846).

upload_max_filesize = 2M

Change the value like below:

upload_max_filesize = 20M

Then find the following line (line 694).

post_max_size = 8M

Change the maximum size of POST data that PHP will accept.

post_max_size = 20M

Save and close the file. Alternatively, you can run the following two commands to change the value without manually opening the file.

sudo sed -i 's/upload_max_filesize = 2M/upload_max_filesize = 20M/g' /etc/php/7.4/fpm/php.ini

sudo sed -i 's/post_max_size = 8M/post_max_size = 20M/g' /etc/php/7.4/fpm/php.ini

Then restart PHP-FPM.

sudo systemctl restart php7.4-fpm

How to Send Emails in WordPress

Your WordPress site needs to send emails like account registration emails, password-resetting emails, comment notification emails, etc. Instead of using expensive third-party solutions like Gsuite to create professional email addresses for your website, you can follow this iRedMail tutorial to set up your own mail server with your own domain name, so you can have unlimited mailboxes and send unlimited emails without breaking the bank.

Note that it’s a good practice to install mail server and WordPress on two different virtual private servers because you don’t want the mail server to slow down your WordPress site speed, and the mail server will leak the IP address of your WordPress site if they are on the same virtual private server, which means hackers can bypass any CDN (Content Delivery Network) you are using and launch DDoS attack directly at your origin server.

Once your mail server is up and running, you can install an SMTP plugin in WordPress, so it can connect to your mail server and send emails. Go to your WordPress dashboard -> Plugins, click Add New to install a new plugin.

wordpress add new plugin

Then type in WP Mail SMTP in the search box. Install and activate the WP Mail SMTP by WPForms plugin.

wp mail smtp

Reload the WordPress dashboard web page, you will see WP Mail SMTP on the left menu bar. Click on it and select Settings.

wp mail smtp settings

Then scroll down to the Mailer section. By default, the PHP mailer is selected. We need to change it to Other SMTP.

wordpress send emails

Scroll down and you will need to enter the SMTP settings.

  • Enter the hostname of your mail server.
  • Select TLS as Encryption.
  • Use port 587.
  • Enable Authentication.
  • Enter an email address of your domain and the password.

wordpress set up your own email server

After saving the settings, you can test email sending by logging out the WordPress dashboard, and click lost your password link to send a password-resetting email.

wordpress lost your password

Next Steps

I hope this tutorial helped you install WordPress on Ubuntu 20.04 with Apache, MariaDB and PHP7.4. As always, if you found this post useful, then subscribe to our free newsletter. 🙂

Backup is important in case of hacking, data center disasters, etc. You should have a backup strategy for your WordPress site.

Linux Server Performance Tuning and Monitoring

Take care 🙂

Rate this tutorial
[Total: 12 Average: 4.8]

13 Responses to “Install WordPress on Ubuntu 20.04 with Apache, MariaDB, PHP7.4 (LAMP)

  • Gary Bisaga
    6 years ago

    Another flawless tutorial! Thank you!

  • Vineeth
    5 years ago

    Hi
    Thank you for the neat instructions. However I get stuck at the last part. Can’t get to the wordpress installation wizard in the browser.

    “Set a correct A record for your domain name, then enter your domain name in browser address bar.” Can you please explain this? Is this relevant for local testing. I don’t have a domain, I just want to test locally.

    ” ServerName example.com” Am I supposed to replace ‘example.com’ with ‘localhost’ or just the domainname that I put after /www/var/ during installation?

    I am still getting the “Apache2 Ubuntu Default Page” when I go to localhost in the browser. or is there something else I am supposed to type in the browser to access the wordpress installation?

    Thank you !

    • Xiao Guo An (Admin)
      5 years ago

      localhost will bring you to the default Apache virtual host.

      If you don’t have a domain name and just want to install WordPress on your local computer, you can create a local DNS entry in /etc/hosts file like below.

       127.0.0.1 localhost example.com www.example.com

      So you can type in example.com in the browser address bar and it will take you to your WordPress installation.

  • I have a local Ubuntu 18.04 server on the same LAN as my windows laptop.
    I have followed the below procedures:

    How to Install LAMP Stack on Ubuntu 18.04 Server/Desktop

    How to Install phpMyAdmin with Apache (LAMP) on Ubuntu 18.04


    And all appears to be working fine. I can reach the apache splash page and http://192.168.1.134/phpmyadmin/

    I would like to create a local wordpress instance on the server to learn how to build webpages.
    Will this procedure work for Ubuntu 18:04?

    • Fantastic website with flawless instructions.

      by carefully reading through the instructions, I have converted my Intel NUC into a functioning web server with almost no previous linux experience.

      Note: This procedure does work for ubuntu 18.04. However the latest wordpress release recommends PHP7.3 so I upgraded that.

  • Error establishing a database connection

  • Hey, Amazing tutorial, Thank you!!

    Just one tip that I can provide using the tutorial is to ensure to disable the 0000-default.conf file using “a2dissite” command after setting up the wordpress config file.

    The browser kept going to the default page even after I was completed the tutorial and could not get into the wordpress initial setup.

    Everything else is 10/10 – Keep it up and Thank you again!
    -DJ

    • Niclas
      1 year ago

      Thanks! I needed to do exactly that to be able to access …/wp-admin/install.php. Well not exactly, only 3 zeros:

      “sudo a2dissite 000-default.conf”

      Should maybe be added to the tutorial?! @LinuxBabe

  • the-north
    2 years ago

    simply O-mazing instruction !!
    The definition “Top To Bottom”, real bottom email stuff.
    Folks, do not waste time anywhere. ubuntu/wordpress/ssl/email, these stuff is so tricky that you can make a mistake easily or miss a command which is very ambiguous.

    you go to lots of how-to sites, very difficult to get them all consolidate under a big umbrella.
    Terrible thingy is where i can go/fix/re-do/undo if some thing went wrong.

    This article is superb, really.

    I finally tried to register into my ssl wordpress site with ubuntu20.04 on oracle cloud, successfully got mail to login. no other web pages i visited for this matter.

    Appreciate you.

  • Hey man,

    Just to say, usefull article without any misguided lines, everything works fine as always.

    Nice job!

  • zongboa
    2 years ago

    Hello.
    I have read your NextCloud setup tutorial and wordpress setup tutorial. How do I integrate these two on one server? How should I fix it? thanks.

  • I had this working perfectly using your directions to run a local server.

    Now that I’m coming back to it, I keep getting a 503 ‘Service Unavailable’ error. Any idea what is going on? I tried starting from scratch and it is still happening.

    「wdm」: Compiled successfully.
    ServerError: Service Unavailable
        at eval (webpack-internal:///./node_modules/@frontity/wp-source/src/libraries/api.ts:31:184)
        at runMicrotasks ()
        at processTicksAndRejections (internal/process/task_queues.js:97:5)
        at Object.eval (webpack-internal:///./node_modules/@frontity/wp-source/src/libraries/handlers/postTypeArchive.ts:7:16)
        at eval (webpack-internal:///./node_modules/@frontity/wp-source/src/actions.ts:25:1) {
      status: 503,
      statusText: 'Service Unavailable'
    }
    
    

Leave a Comment

  • Comments with links are moderated by admin before published.
  • Your email address will not be published.
  • Use <pre> ... </pre> HTML tag to quote the output from your terminal/console.
  • Please use the community (https://community.linuxbabe.com) for questions unrelated to this article.
  • I don't have time to answer every question. Making a donation would incentivize me to spend more time answering questions.

The maximum upload file size: 2 MB. You can upload: image. Links to YouTube, Facebook, Twitter and other services inserted in the comment text will be automatically embedded. Drop file here