Install LEMP Stack For WordPress on Ubuntu 22.04 or 20.04
Step 1: Update Ubuntu Before WordPress Installation
Begin your WordPress installation on your Ubuntu server smoothly and successfully by running the standard update command. Running this command updates your system, minimizing the risk of conflicts during the WordPress installation process, as WordPress is extensive and intricate.
To execute the standard update command, open your terminal and input the following command:
sudo apt update && sudo apt upgrade
This command will update any outstanding packages and upgrade your system.
Step 2: Install Initial Packages For WordPress on Ubuntu
Ensure you have installed the following packages before proceeding:
sudo apt install curl git wget unzip zip
Step 3: Install Nginx on Ubuntu – LEMP Stack Part 1
To set up a LEMP stack, first install Nginx by running the command:
sudo apt install nginx
Typically, the system enables the Nginx service by default upon installation. Nonetheless, run the following command to ensure its correct operation:
systemctl status nginx
Activate the Nginx service, if not already active, by using the following command:
sudo systemctl enable nginx --now
Additional: Install Nginx Mainline For WordPress on Ubuntu
To optimize your WordPress performance, use the latest Nginx mainline version instead. You can follow the guide on installing Nginx Mainline on Ubuntu 22.04 or 20.04 LTS. This version offers additional features and improvements to enhance your website’s speed and overall performance.
Configure UFW Firewall for Nginx and WordPress on Ubuntu
Securing your Nginx server and allowing access to default web ports requires configuring the UFW firewall. Nginx offers profiles for quick UFW configuration for its use.
Ensure UFW is installed on your Ubuntu system with the command:
sudo apt install ufw
After installation, enable UFW on your system. By default, UFW will deny all incoming and allow all outgoing connections. To enable the firewall, use the following command:
sudo ufw enable
To see the available Nginx profiles, run the following command:
sudo ufw app list
The output shows that Nginx runs on port 80 (HTTP), Nginx Secure runs on port 443 (HTTPS), and Nginx Full combines both. To enable both HTTP and HTTPS access, use the Nginx Full profile:
sudo ufw allow 'Nginx Full'
However, depending on your specific needs, you may want to adjust the profile. For example, if you only require HTTPS access, use the Nginx Secure profile:
sudo ufw allow 'Nginx Secure'
Or, if you only require HTTP access, use the Nginx HTTP profile:
sudo ufw allow 'Nginx HTTP'
Step 4: Install MariaDB on Ubuntu – LEMP Stack Part 2
The second stage of the LEMP installation involves installing the database component. MariaDB is the preferred choice in the LEMP stack over MySQL due to its improved performance and other advantages. However, suppose you wish to install a different version of MariaDB from the official repositories provided by MariaDB.org. In that case, our guide on installing MariaDB 10.x on Ubuntu 22.04 or 20.04 LTS can improve the performance of your WordPress installation.
To install MariaDB, execute the following command in your terminal.
sudo apt install mariadb-server mariadb-client
Verifying the status of the MariaDB service after installation is crucial, just as you did for Nginx, to ensure its correct functionality without errors:
systemctl status mariadb
If MariaDB is inactive, run this command to activate the service and enable it on the system boot immediately:
sudo systemctl enable mariadb --now
Secure MariaDB with Security Script on Ubuntu
Configuring the security of your MariaDB installation is a critical step toward maintaining the integrity and confidentiality of your data. By default, new installations of MariaDB often have weak security settings, making them vulnerable to malicious attacks. Fortunately, running the installation security script can help to secure your database and prevent potential exploitation.
To begin, launch the mysql_secure_installation script by executing the following command:
sudo mysql_secure_installation
Now, proceed to configure the MariaDB security script settings. Set the root password, restrict remote access from external sources, remove anonymous user accounts, and eliminate the test database. These actions secure your MariaDB installation and prevent potential security threats.
Example:
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!
Step 5: Install PHP on Ubuntu – LEMP Stack Part 3
You must install the PHP service to set up the LEMP stack successfully. The service acts as a mediator between Nginx and MariaDB, using PHP-FPM and additional modules WordPress requires. If you prefer a different version of PHP that meets your requirements, refer to our guide on installing PHP on Ubuntu 22.04 or 20.04 LTS.
To install PHP and PHP-FPM with the necessary modules on your Ubuntu system, run the following command in your terminal:
sudo apt install php php-fpm php-mbstring php-bcmath php-xml php-mysql php-common php-gd php-cli php-curl php-zip php-imagick php-ldap php-intl
After installation, it is essential to verify the status of the PHP service as you did for MariaDB and Nginx to ensure it is functioning correctly without any errors. In this example, the command is specific to the version of PHP installed, which is PHP 8.1:
systemctl status php8.1-fpm
The output should look like this:
Install WordPress Backend on Ubuntu 22.04 or 20.04
Create WordPress Directory Structure
To begin the installation of WordPress on your LEMP stack, you can visit the official WordPress.org download page and locate the “latest.zip” download link. An alternative option is to use the following command to download the latest version of WordPress:
wget https://wordpress.org/latest.zip
Next, you can unzip the downloaded WordPress archive to the /var/www/html directory:
sudo unzip latest.zip -d /var/www/html/
To ensure that WordPress has the correct write permissions, you must set the directory owner permissions to WWW. You can do this by running the following command:
sudo chown -R www-data:www-data /var/www/html/wordpress/
After setting the chown permission, it’s essential to set the chmod permission for the WordPress folders and files. This step is crucial to ensure that the WordPress site functions correctly without any issues related to write permissions.
Use the following commands to set the chmod permission for the folders and files:
For folders:
sudo find /var/www/html/wordpress -type d -exec chmod 755 {} \;
For files:
sudo find /var/www/html/wordpress -type f -exec chmod 644 {} \;
These commands establish the correct permissions for WordPress files and directories. They assign 755 permissions to folders, allowing owners to read, write, and execute while granting others read and execute access only. Similarly, they allocate 644 permissions to files, permitting owners to read and write, with read-only access for others.
Create a Database for WordPress on Ubuntu
First, create a database to run WordPress on your server. Since you previously installed MariaDB during the LEMP stack setup, use it to create a new WordPress database. Open your terminal, enter the following command, and access the MariaDB shell as root to begin the process:
sudo mariadb -u root
Once you have accessed the MariaDB shell, enter the following command to create a new database with any desired name. In this guide, we will name it “WORDPRESSDB.”
CREATE DATABASE WORDPRESSDB;
After creating the database, create a new user account for WordPress with the following command. It’s essential to create a new user account for each website as a security measure to protect your databases in case of a breach.
CREATE USER 'WPUSER'@localhost IDENTIFIED BY 'PASSWORD';
Replace “WPUSER” and “PASSWORD” with the desired username and password. Do not copy and paste the default user/pass above for security reasons.
Finally, assign the newly created user account access to the WordPress website database only with the following command:
GRANT ALL PRIVILEGES ON WORDPRESSDB.* TO WPUSER@localhost IDENTIFIED BY 'PASSWORD';
With all database configuration settings complete, you must flush the privileges to ensure the new changes take effect. Run the following command to flush the privileges:
FLUSH PRIVILEGES;
Lastly, exit the MariaDB shell by typing:
EXIT;
Set WordPress Configuration Files on Ubuntu
Setting the WordPress configuration files is an essential step in the installation process. It involves renaming the sample wp-config.php file and entering the necessary configuration details.
To start, navigate to the WordPress directory using the following command:
cd /var/www/html/wordpress/
Next, copy the wp-config-sample.php to wp-config.php. Keeping the sample in case you need to start over is good. Run the following command to copy the file:
sudo cp wp-config-sample.php wp-config.php
Using a text editor, bring up the newly copied wp-config.php file:
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 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');
Adjust your dedicated server or VPS memory limits to increase or decrease the 256 MB memory limit. However, increase it only in small amounts, such as 128 MB, 256 MB, or 512 MB.
Example of what your configuration may look like:
Configure WordPress Security Salt Keys on Ubuntu
Setting up WordPress security salt keys is vital for the security of your WordPress installation. These keys fortify your WordPress site by enhancing the security of user authentication and data encryption.
Visit the WordPress secret-key API at https://api.wordpress.org/secret-key/1.1/salt/ to generate security salt keys. Replace the example lines in the wp-config.php file with these new keys immediately after generation.
Avoid using the example lines; they serve as references only. Using pre-generated salt keys exposes your site to attacks, so always generate unique keys for each WordPress installation.
Open your wp-config.php file with a text editor to add the new security salt keys:
sudo nano /var/www/html/wordpress/wp-config.php
Then, find the lines in the file that correspond to the example keys:
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');
Replace each example phrase with your unique salt key generated from the WordPress API. Save and exit the file once you’ve replaced all the example phrases.
Create Nginx Server Block For WordPress on Ubuntu
To install WordPress through the web UI, you must first configure your Nginx server block. It is essential to pay attention to the settings listed below, particularly “try_files $uri $uri/ /index.php?$args;”, as omitting the “?$args” may cause issues with the REST API of WordPress.
To create a new server configuration file, use the following command, replacing “example.com” with your domain name:
sudo nano /etc/nginx/sites-available/example.com.conf
The Nginx configuration file should include “location ~ .php$” to ensure proper functionality. Below is an example configuration file; make sure to update the root path, as well as “www.example.com” and “example.com” to reflect your domain names:
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;
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;
}
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, if you have installed a different version of PHP and PHP-FPM, such as PHP 7.4, 8.0, 8.2, 8.3, etc., or your version of Ubuntu uses a different default version, you should replace the line “fastcgi_pass unix:/run/php/php8.1-fpm.sock;” with the appropriate version. For example, for PHP-FPM 8.2, the line would be “fastcgi_pass unix:/run/php/php8.2-fpm.sock;”
Nginx WordPress Server Block Explained
You may find information on the server block example below for users installing Nginx and WordPress for the first time.
- Basic server settings:
- This section defines the basic settings for the server block, including the IP address and port that Nginx will listen on and the server name(s) that the block will apply to.
- The “root” directive specifies the root directory where the website files will be located, in this case, “/var/www/html/wordpress”.
- The “index” directive specifies how Nginx should look for index files when serving the site.
- Location settings:
- This section contains the “location” blocks, which define how Nginx should handle requests for different URLs.
- The first “location” block handles requests to the root URL of the site and uses the “try_files” directive to look for the requested file and, if it’s not found, to pass the request to the WordPress index.php file.
- The second “location” block handles requests for the WordPress sitemap.xml file and passes the request to the WordPress index.php file if the file isn’t found.
- PHP handling settings:
- This section defines how Nginx should handle PHP files, using the “location ~ .php$” block to match requests for files ending in “.php”.
- The “fastcgi_pass” directive specifies the location of the PHP-FPM socket file, which is used to communicate between Nginx and PHP-FPM.
- The “fastcgi_param” directive sets the value of the “SCRIPT_FILENAME” parameter to the location of the requested PHP file.
- The “include” directives load additional configuration files for the FastCGI module.
- The “fastcgi_buffer_size” and “fastcgi_buffers” directives set the buffer size to pass data between Nginx and PHP-FPM.
- The “fastcgi_intercept_errors” directive allows Nginx to intercept and handle PHP errors.
- Gzip compression settings:
- This section defines the settings for Gzip compression, which can be used to reduce the size of files sent to the client.
- The “gzip” directive enables Gzip compression.
- The “gzip_comp_level” directive sets the level of compression to use.
- The “gzip_min_length” directive sets the minimum size of a file to be compressed.
- The “gzip_proxied” directive specifies which types of requests should be compressed.
- The “gzip_types” directive lists the MIME types that should be compressed.
- File caching settings:
- This section defines settings for caching static files, which can help to speed up the website by reducing the number of requests to the server.
- The first “location” block sets the expiration time for files used for assets and media, such as images and videos.
- The second “location” block sets the expiration time for files used for fonts and SVGs.
- The “access_log” and “log_not_found” directives control the logging of these requests.
- The “add_header” directive sets the “Access-Control-Allow-Origin” header to allow the loading of fonts and SVGs from other domains.
- .htaccess file blocking:
- This section blocks access to files starting with “.ht”, typically used for sensitive server configuration files.
To finish off this the Nginx server block configuration, you will need to enable the Nginx configuration file from “sites-available” by creating a symlink to “sites-enabled” using the following command, replacing “example.conf” with your configuration file name:
sudo ln -s /etc/nginx/sites-available/example.com.conf /etc/nginx/sites-enabled/
Perform a dry run to check for any errors using the following command:
sudo nginx -t
If everything checks out, restart the Nginx service:
sudo systemctl restart nginx
PHP.ini Configuration
Adjusting your PHP configuration is crucial for optimal WordPress use. You should increase the maximum upload size, post size, and memory limit to accommodate WordPress media files. You can also adjust the maximum execution time and input variables.
To do this, first, open your php.ini file using your terminal. Note that the location may differ depending on your PHP version number.
Here are some examples of common PHP version paths to php.ini:
sudo nano /etc/php/7.4/fpm/php.ini
sudo nano /etc/php/8.0/fpm/php.ini
sudo nano /etc/php/8.1/fpm/php.ini
sudo nano /etc/php/8.2/fpm/php.ini
sudo nano /etc/php/8.3/fpm/php.ini
Next, find the following lines and adjust them to your needs:
##increase this to the maximum file size you want to upload, recommended 50 to 100MB##
upload_max_filesize = 100M
##increase this to the maximum post size you want to allow, recommended 50 to 100MB##
post_max_size = 100M
##increase this to the maximum execution time, recommended 150 to 300 seconds##
max_execution_time = 300
##increase this to the maximum GET/POST/COOKIE input variables, recommended 5000 to 10000##
max_input_vars = 5000
##increase this to the maximum memory limit, recommended 256MB or 512MB. Note that you should ensure your system has enough RAM before raising this.##
memory_limit = 256M
After adjusting your PHP settings, restart your PHP-FPM server using the appropriate command for your version of PHP.
It would be best to modify the Nginx server block to allow large body sizes. Reopen your server block and add the following line:
- client_max_body_size – this should be set to the maximum upload size you set in upload_max_filesize.
If you followed the example server block, it set your max file size to 100MB. Refer to the example as a guide if unsure.
After changing the PHP configuration file, restart the PHP-FPM server to implement the new settings. The restart command varies with the PHP version. Identify and use your PHP version number in the command, even if the examples below do not list it.
Below are commands to restart PHP-FPM for different PHP versions:
sudo systemctl restart php7.4-fpm
sudo systemctl restart php8.0-fpm
sudo systemctl restart php8.1-fpm
sudo systemctl restart php8.2-fpm
sudo systemctl restart php8.3-fpm
Install WordPress Front-end on Ubuntu 22.04 or 20.04
Complete the backend setup and configuration, then install WordPress on your domain.
Start by entering the installation domain name, like https://www.yoursite.com. You can also use https://www.yoursite.com/wp-admin/install.php.
Post a Comment
Post a Comment