Objective

Install Nginx Web Server (LEMP) on Ubuntu 18.04. In particular, this Linux web server install guide shows you how to install Nginx, how to install MariaDB and how to install PHP.

Distributions

Ubuntu 18.04 Bionic Beaver

Requirements

A working install of Ubuntu 18.04 with root privileges

Difficulty

MEDIUM

Conventions

  • # - requires given linux commands to be executed with root privileges either directly as a root user or by use of sudo command
  • $ - requires given linux commands to be executed as a regular non-privileged user

Introduction

If you want to run PHP-based websites on Linux, Apache isn't your only option. Nginx is a faster, lighter weight, web server that's fairly easy to configure and get running. Plus, it's excellent at handling other tasks like load balancing, server optimization, and acting as a reverse proxy. Actually, Nginx is a top choice among startups for hosting their web applications. Setting Nginx up to host PHP on Ubuntu 18.04 is very simple, and you only need a few packages installed to get started.

Installation

Before you can do anything, you should install everything that you need first. There are only a couple of packages that you need. Plus, Ubuntu 18.04 has fairly current versions of everything right in its default repositories, so you don't need to worry about tracking down external repositories.
$ sudo apt install mariadb-server nginx php-fpm php-mysql
During the install, you'll be asked to set up an admin account for MariaDB/MySQL. Pick a secure and memorable passphrase. You should take a minute to start and enable PHP-FPM now too.
NOTE: Update the below commands with your installed PHP version! To check your PHP version execute php --version command.
$ sudo systemctl start php7.1-fpm
$ sudo systemctl enable php7.1-fpm


Set Up Your Database

Now, you can sign in to your newly created database.
$ mysql -u root -p
Enter the password that you set up during the installation. You'll be dropped into the MySQL console. You can do everything that you need from there. Before anything, make your actual database.
mysql> CREATE DATABASE `bionic_lemp`;
Then, make a regular use to run the database.
mysql> CREATE USER `site_admin`@`localhost` IDENTIFIED BY 'your_password';
Finally, grant your new user the privileges to actually use the database.
mysql> GRANT ALL ON bionic_lemp.* TO `site_admin`@`localhost`;
When you're done, flush the privileges and exit the console.
mysql> FLUSH PRIVILEGES;
mysql> exit;

Configure Nginx

All of the Nginx configurations are located in /etc/nginx. They are broken down to simplify the configuration process. The two that you need to worry about are the main nginx.conf file and the site-specific one that you'll create for your website. That one, you'll put in the sites-available directory.

Create a new file for your site in /etc/nginx/sites-available. The full path should be something like /etc/nginx/sites-available/your-site.

Start off the file by creating a server block. Nginx uses server blocks to designate a new web application instance for it to listen for.
server {
}
The first things that you should put in your server block are the listen lines. They tell Nginx what port to listen on.
listen 80 default;
listen [::]:80 default;
These will cover both IPv4 and IPv6 connections. Remove the default specifies that this is the default server. You can only have one default, so make sure to select the right one, if you're hosting multiple sites.

Next, tell Nginx what domain name to associate with the site. If you're just doing this locally, use localhost. Otherwise, use your domain name.
server_name your-site.com;
If you would like Nginx to automatically redirect requests with the www to the same server block. Add the following block before the beginning of your current server block.
server {
    listen       80;
    server_name  www.your-site.com;
    return       301 http://your-site.com$request_uri;
}


Next, specify the root directory of your site and what the site index file will be named. These lines tell Nginx to look for the site in /var/www/your-site and begin with any file called index.php or index.html.
root /var/www/your-site/;
index index.php index.html;
It's also a good idea to set up individual error logs for each of your sites. Specify them here too.
access_log /var/log/nginx/your-site.access_log;
error_log/var/log/nginx/your-site.error_log;
Create a location block to tell Nginx to raise a 404 error whenever files aren't found. location blocks go inside server blocks and tell Nginx how to handle specific file types in certain locations.
location / {
	try_files $uri $uri/ =404;
}
The last thing that you need to do is tell Nginx how to handle your PHP files. Create another location block for that.
NOTE: Update the below configuration with your installed PHP version! To check your PHP version execute php --version command.
location ~ \.php$ {
	include snippets/fastcgi-php.conf;
    fastcgi_pass unix:/var/run/php/php7.1-fpm.sock;
}


Ubuntu Bionic Nginx Configuration LEMP

That's all that you need. Save and exit the file. It's also probably a good idea to create that site directory now.
$ sudo /var/www/your-site
Give Nginx ownership of it too.
$ sudo chown -R www-data:www-data /var/www/your-site
Now, remove the symlink for the default configuration in /etc/nginx/sites-enabled.
$ sudo rm /etc/nginx/sites-enabled/default
Then, create a new symlink for your site's configuration.
$ sudo ln -s /etc/nginx/sites-available/your-site /etc/nginx/sites-enabled/
Restart Nginx for the changes to take effect.
$ sudo systemctl restart nginx


Test It Out

The best way to test that everything is working is by putting a simple PHP script in your site directory and having it connect to your database. Create the following file at /var/www/your-site/index.php.
<?php echo '<h1>Page loaded with PHP!</h1>';
$conn = mysqli_connect('localhost', 'site_admin', 'your_password');

if(!$conn){
	die('<h2>Error: </h2>' . mysqli_connect_error());
}else{
	echo '<h2>Successfully Connected to MySQL Database!</h2>';
}
?>


Ubuntu Bionic Running LEMP

Navigate to your site using your web browser. If you see the success message saying that you successfully connected to MySQL, your server is properly configured.

Closing Thoughts

Configuring Nginx takes some time, but it's worth it. It's not only faster than other web servers, it gives you loads of options and fine-grained control. It's also easy to configure Nginx to host web applications written in other languages like Python and Ruby right along side your PHP ones. Nginx is easily one of the best choices for modern web applications.
Please refer all article related questions to:

You may also be interested in: