Skip to content
OSULZER.AT
Server25 min read· updated March 2, 2022

Setting Up an Ubuntu 18.04 Server with Nginx, MySQL, PHP, and SSL

Step-by-step guide to setting up and securing an Ubuntu 18.04 web server with Nginx, MySQL, PHP and SSL. Works for vServers, root servers and droplets.

This post is from 2019 - some of its content may be outdated by now.

A dedicated web server lets you deliver websites faster, install your own software, and make all the settings yourself. You are not limited by a hosting provider’s restrictions, but in return you have to take care of configuring and securing the server yourself. This guide can be applied to vServers, root servers, or droplets. Almost all hosting providers offer various Linux distributions that can be installed automatically on the respective server. The only requirement for following this guide is that you use Ubuntu version 18.04. Besides the server itself, we of course also need SSH access to the server and a root user. You should receive this information through your provider’s web interface after setup. Once we have all the required information, we can get started. If your provider gives you the option to use SSH keys for logging in, you should definitely use it. The login procedure differs slightly from provider to provider in this case, and in most cases the provider describes it directly.

In this guide, I am working with a server hosted at DigitalOcean. If you are interested, you can create an account via this link (affiliate link). If you register through the link, you receive 100 US dollars in credit that you can use over a period of 60 days. After the 60 days, the credit and all associated services expire. If you are happy with the service, you can buy additional credit. As soon as you top up more than 25 US dollars, I receive 25 US dollars credited to my account for the referral. This does not result in higher prices or any other disadvantages for you. Of course, you can also use other providers such as Hetzner. The decision is up to you.

Are you no longer happy with your website? Are you struggling with long load times on your website or web shop, or do you need a modern online presence? I offer website development, search engine optimization, and WordPress plugin development in Vienna and Lower Austria.

Basic Server Setup

Logging In

Once our server has been set up and we have the required login credentials or SSH keys, we can get started. We use SSH for remote administration. Linux and Mac users can connect directly through the terminal. Windows users can use tools such as PuTTY or MobaXterm. The advantage of MobaXterm is that you can manage profiles for the individual servers more easily. I use MobaXterm for administration, so the screenshots in this guide come directly from it.

We start the connection to our server (via terminal) with the following command (if you use SSH keys, you also need to specify the path to the keys). Depending on the software you use, there are different steps to go through for logging in. If your provider does not describe the respective options, you can also ask Google for the procedure that applies to your case.

ssh root@ip_des_servers

If you connect to the server with a password, you may be asked to change your password. Simply follow the steps shown on screen. Also create a list now, for example in Excel, where you store the most important passwords.

After a successful login, your SSH session should show something like the following.

Firewall

After a successful login, we start with the initial configuration of our firewall. Ubuntu ships with a suitable solution called UFW. The apps used in this guide each register their own profiles, which can be used easily in combination with UFW.

To see which apps are currently installed and can be controlled directly via UFW, we enter the following command:

ufw app list

The command should give us the following output:

Available applications:
  OpenSSH

OpenSSH is currently the only application on the server that can be configured via UFW. Our firewall is not yet enabled. Before we can enable the firewall, however, we need to allow OpenSSH so that we do not lock ourselves out. We allow it with “ufw allow AppName”. For OpenSSH, the command looks like this:

ufw allow OpenSSH

The output should look like this:

Rules updated
Rules updated (v6)

Our rules have been updated successfully, so it is time to enable the firewall. To do that, we enter the following command.

ufw enable

Before the firewall is enabled, you will be asked a security question that you need to confirm with “y”. After that, you should see the following output.

Firewall is active and enabled on system startup

Perfect. Now let us quickly take a look at the current status of our firewall using:

ufw status

This now shows us the registered apps with their respective firewall settings. In our case, the list is quite short. If you have already installed additional software, the list could be a bit longer.

Below is an image showing the last inputs.

Creating a User Account

On Linux systems, the root user is the unrestricted administrator of the system. This means the account has access to all aspects of the system and can therefore influence them negatively, whether intentionally or unintentionally. For this reason, right after logging in successfully, we create a new user whom we add to the sudo group. This user then does not receive all the rights granted to the actual root user.

To create a new user, we enter the following command. In our case, we name the user “osulzer”.

adduser osulzer

We confirm the input with Enter and are asked for a password. Use a strong password. If you do not use a password manager yet, now may be a good time to start. Alternatively, you can create your own password and store it in a safe place. After the password, you will be asked for further details about the user. You can either provide more information here or simply skip ahead with the Enter key.

Now we add the new user to the sudo group. Afterwards, our user can run “sudo” commands.

usermod -aG sudo osulzer

The output of your SSH session should now look something like this.

Setting Up SSH Access for the New User

For any work on our server, we will use our new user from now on. To be able to use this user for logging in to our server directly, a few settings still need to be made. If you only log in to the server with a username and password, it is enough to enter the connection command “ssh osulzer@ip_des_servers” in the terminal and connect. The secure method using SSH keys requires further preparation.

Attention: For security reasons, stay logged in to your server as the root user for now. So do not close the window until the new login has been tested and works.

Enabling SSH Key Authentication

In the future, we only want to log in with our newly created user. To do that, we need to configure the SSH keys that are currently assigned to root for our new user. We use rsync for this so that the access permissions are preserved when copying the keys. Please stay logged in with your root SSH session, because if an error occurs while copying the keys, you could lock yourself out of the server. To copy the keys, we use the following command. In your case, you need to replace the places where I entered “osulzer” with the username you chose. Before you enter it, a quick clarification: the part of the command “chown=osulzer:osulzer” does not mean “username:password” but “username:user group”. So in our case, you need to enter the username twice, separated by “:”. Also make sure the part “~/.ssh” has no slash at the end, otherwise the contents of the folder are copied instead of the folder itself.

rsync --archive --chown=osulzer:osulzer ~/.ssh /home/osulzer

After running the command, you should be able to log in via SSH with your new user. Unlike with the root user you have used so far, with your new user you need to add the prefix “sudo” at the beginning of any command that makes changes to the system. The command then asks for the password you entered when creating the user.

From now on, we only work through this user, so close your root session with the server and continue with the new SSH session in which you are logged in with the user you created.

To configure Nginx and SSL, we need a domain that points to our server. Depending on where you registered your domains, there are different settings and interfaces for changing the domain’s DNS settings. What matters is that the domain’s “A” record points to the server’s IP address. Below is a short explanation of the records.

Name Type Content
*.euredomain.com A server_ip_adresse
www.euredomain.com A server_ip_adresse
euredomain.com A server_ip_adresse

Changing these settings can take a few hours. In the meantime, you can continue with the installation of Nginx until we get to the point of configuring the server block for the domain. From then on, your domain should ideally already point to your new server.

Quick Tip:

You can reset the DNS cache on your computer to get the updated addresses sooner.

Windows Users

Open a command prompt and enter the following command:

ipconfig /flushdns

Mac OS X

sudo dscacheutil -flushcache

Linux Users

sudo /etc/init.d/nscd restart

Installing Nginx

If you have only worked with regular web hosting so far, you may not know what Nginx is. Nginx offers better performance and saves important server resources compared to Apache. Disadvantages compared to Apache include, for example, the greater effort to install additional modules and the lack of an option to change server variables in an .htaccess file. Which solution you ultimately use for your server is up to you. In this tutorial, we work with Nginx.

Before we start installing Nginx, we update our local package index. To do that, we enter the following command.

sudo apt update

If you are shown at this point that updates are available, you can install them with the following command.

sudo apt upgrade

Now we install Nginx directly from the Ubuntu repository.

sudo apt install nginx

Shortly after running the command, the system asks whether you want to download the new files. Confirm with “y”.

Ubuntu starts Nginx right after installation, so we do not need to register the service separately. Before we can test requests over HTTP, however, we still need to allow Nginx in our firewall. To do that, let us first take a look at the profiles registered by Nginx in the UFW firewall.

sudo ufw app list

Output:

Available applications:
  Nginx Full
  Nginx HTTP
  Nginx HTTPS
  OpenSSH

Nginx has provided us with several profiles. If we want, we can block requests that come in over HTTP and only allow HTTPS requests. Since we will redirect HTTP requests to HTTPS later and therefore do not want to block the requests outright, we choose the “Nginx Full” profile to allow. To do that, we enter the following command.

sudo ufw allow 'Nginx Full'

Output:

Rule added
Rule added (v6)

The server should now respond to HTTP requests. Start the browser of your choice and navigate to the IP address or to the domain that points to the server’s IP address. If everything worked, you should see the following message.

Congratulations, Nginx is running, but we are not done yet. Unlike with Apache, when using Nginx we have to install PHP ourselves. For this, we use php-fpm, which stands for “FastCGI process manager”. Nginx forwards PHP requests to this software in order to execute PHP code. Besides php-fpm, we also install the matching interface as well so that we can later access our MySQL database through PHP. When this guide was written, the following command installed PHP version 7.2.

sudo apt install php-fpm php-mysql

Now the required packages are installed, but we still need to tell Nginx that these packages should be used. Nginx uses so-called server blocks, which let you run, for example, multiple websites on one server. The individual websites can use separate configurations. After installation, Nginx points to the directory “/var/www/html”, so at the moment the server points directly to the contents of that folder. For our domain, we create a separate directory with a suitable folder structure. The following command does that for us using the -p parameter.

sudo mkdir -p /var/www/euredomain.com/html

Next, we assign ownership to the $USER environment variable.

sudo chown -R $USER:$USER /var/www/euredomain.com/html

Now we also set the access permissions.

sudo chmod -R 755 /var/www/euredomain.com

We use the folder created under /var/www/euredomain.com/html as the starting point for our website. Before that works, however, we still need to configure Nginx. To do that, we create a new server block under /etc/nginx/sites-available/.

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

Now paste in the following code as the starting configuration.

server {
	listen 80;
	listen [::]:80;

	root /var/www/euredomain.com/html;
	index index.php index.html index.htm index.nginx-debian.html;

	server_name euredomain.com www.euredomain.com;

	location / {
		try_files $uri $uri/ =404;
	}

	location ~ \.php$ {
		include snippets/fastcgi-php.conf;
		fastcgi_pass unix:/var/run/php/php7.2-fpm.sock;
	}

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

We use the Nano editor. It saves your input with “CTRL+O -> Enter” and then closes the window with CTRL+X.

What Exactly Are We Doing Here?

listen - Our server block listens for requests on port 80 and then serves the contents of the directory /var/www/euredomain.com/html.

root - Next, we specify which folder Nginx should look in for files and which files are allowed as index.

server - Here we specify that the block applies to requests that come in via http://www.euredomain.com and http://euredomain.com.

location / specifies that we return a 404 error page if no index file was found.

location ~ \.php$ - points to the program that takes care of interpreting PHP. In our case, php7.2-fpm.sock is included.

location ~ /\.ht - Nginx does not support .htaccess files and would output them directly as plain text. With this setting, we prevent them from being served to visitors.

To have our new server block run the next time Nginx starts, we need to create a symlink to the new configuration.

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

If you use domains with long names, you should also enable the following Nginx setting. To do that, enter the following command:

sudo nano /etc/nginx/nginx.conf

In the file, we look for the entry “server_names_hash_bucket_size” and remove the # symbol in front of it. Save the file and close the editor.

Before we restart Nginx, we test the new configuration.

sudo nginx -t

If everything worked, the output should look like this.

Now we restart Nginx to activate the new settings.

sudo systemctl restart nginx

Visiting your domain should now show you a 404 error page. Do not panic, the error message is correct, since we do not have any files in our public directory yet. That is quickly changed. We simply create an index.php file.

nano /var/www/euredomain.com/html/index.php

We paste the following into the file and save it.

<?php
phpinfo();

Our server should now output details about the PHP version in use. This means that PHP is being executed successfully.

Since we should not make this information publicly accessible, we delete the index.php file again now.

rm /var/www/euredomain.com/html/index.php

Making Nginx GDPR Compliant

Anonymizing IP Addresses (Problematic)

By default, Nginx stores every request to the server in the access.log file. The visitor’s IP address is stored as well. Since IP addresses count as personal data, we have the option of anonymizing the IP address. For this, we use a small script written by a resourceful StackOverflow user. The problem with the following change: attackers are also anonymized by this method and can therefore no longer be traced. I recommend reducing the retention period of the log files to 7 days (next section) and pointing out the retention period in your privacy notice accordingly.

sudo nano /etc/nginx/nginx.conf

Right after “http {” we insert the following code.

map $remote_addr $ip_anonym1 {
    default 0.0.0;
    "~(?P<ip>(\d+)\.(\d+)\.(\d+))\.\d+" $ip;
    "~(?P<ip>[^:]+:[^:]+):" $ip;
}

map $remote_addr $ip_anonym2 {
    default .0;
    "~(?P<ip>(\d+)\.(\d+)\.(\d+))\.\d+" .0;
    "~(?P<ip>[^:]+:[^:]+):" ::;
}

map $ip_anonym1$ip_anonym2 $ip_anonymized {
    default 0.0.0.0;
    "~(?P<ip>.*)" $ip;
}

log_format anonymized '$ip_anonymized - $remote_user [$time_local] '
'"$request" $status $body_bytes_sent '
'"$http_referer" "$http_user_agent"';

Under “Logging Settings”, you now look for the entry

access_log /var/log/nginx/access.log;

and change it to:

access_log /var/log/nginx/access.log anonymized;

Now save the file and test the changes with

sudo nginx -t

If that worked, we restart Nginx

sudo service nginx restart

Now visit your website once to generate a new entry in the access log. Then we check whether the last digits of the IP address have been zeroed out.

sudo nano /var/log/nginx/access.log

From now on, the last part of the IP address should always be set to 0.

Log files should be deleted after 7 days if they contain personal data. We have already anonymized the data, but changing the retention of log files from 14 days to only 7 days is still not a bad idea. Only a few additional steps are needed for the change. First, we open the relevant configuration file.

sudo nano /etc/logrotate.d/nginx

In the file, we then change the number next to “rotate” from 14 to 7. The contents of the file should then look like this.

/var/log/nginx/*.log {
	daily
	missingok
	rotate 7
	compress
	delaycompress
	notifempty
	create 0640 www-data adm
	sharedscripts
	prerotate
	if [ -d /etc/logrotate.d/httpd-prerotate ]; then \
		run-parts /etc/logrotate.d/httpd-prerotate; \
	fi \
	endscript
	postrotate
		invoke-rc.d nginx rotate >/dev/null 2>&1
	endscript
}

Save the file and close the editor. We do not need to restart any service to apply the changes, since logrotate is run via crontab.

Controlling the Nginx Service from the Command Line

To help you feel a bit more at home with Nginx, here are a few basic commands for controlling the Nginx process.

Stop the Nginx server

sudo systemctl stop nginx

Start the Nginx server

sudo systemctl start nginx

Restart the Nginx server

sudo systemctl restart nginx

Reload Nginx after changing settings

sudo systemctl reload nginx

Disable Nginx autostart

sudo systemctl disable nginx

Enable Nginx autostart

sudo systemctl enable nginx

Nginx Server Logs

If problems occur, Nginx stores error messages, for example, in the following files.

/var/log/nginx/access.log - Contains information about all requests
/var/log/nginx/error.log - Contains all error messages

Setting Up an SSL Certificate

For requests that come in via HTTPS, we need a suitable certificate. We create our certificate ourselves with Let’s Encrypt. All we need for that is a suitable domain that points to the IP address of our server. You can find more details on this further up. To set up the Let’s Encrypt certificate, we use Certbot. To get the latest version of the package, we first add the developers’ repository.

sudo add-apt-repository ppa:certbot/certbot

Confirm the input with Enter and then press Enter once more to confirm the installation. Now we install Certbot for Nginx.

sudo apt install python-certbot-nginx

Thanks to the plugin developed specifically for Nginx, configuring the certificate is done quickly. Change the domain names in the command to your own domain. After confirming, you need to enter an email address and accept the terms of service. Let’s Encrypt then verifies that the chosen domain really points to the server. You also have the option of redirecting all HTTP requests to HTTPS. You should definitely enable this option. Afterwards, the certificate is created and configured automatically for your Nginx server block.

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

Output:

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/euredomain.com
Redirecting all traffic on port 80 to ssl in /etc/nginx/sites-enabled/euredomain.com

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

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

IMPORTANT NOTES:
 - Congratulations! Your certificate and chain have been saved at:
   /etc/letsencrypt/live/euredomain.com/fullchain.pem
   Your key file has been saved at:
   /etc/letsencrypt/live/euredomain.com/privkey.pem
   Your cert will expire on 2019-05-22. 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

That worked. Now visit your domain. The request that previously went through over http:// should now be redirected to https://. As long as your browser does not show a warning about the certificate in use, we are almost done. Let’s Encrypt certificates have an expiration date, so we still need to test whether automatic renewal really works. To do that, we run the following command.

sudo certbot renew -dry-run

Output:

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

Installing and Configuring the MySQL Server

A MySQL database of course must not be missing on our server. So we start the installation.

sudo apt install mysql-server

MySQL offers a wizard that guides us through the installation and draws our attention to various important topics. We start the wizard with the following command:

sudo mysql_secure_installation

Output:

Securing the MySQL server deployment.

Connecting to MySQL using a blank password.

VALIDATE PASSWORD PLUGIN can be used to test passwords
and improve security. It checks the strength of password
and allows the users to set only those passwords which are
secure enough. Would you like to setup VALIDATE PASSWORD plugin?

The Validate Password plugin helps block insecure passwords. We use the plugin and confirm with “y”.

There are three levels of password validation policy:

LOW    Length >= 8
MEDIUM Length >= 8, numeric, mixed case, and special characters
STRONG Length >= 8, numeric, mixed case, special characters and dictionary  file

Please enter 0 = LOW, 1 = MEDIUM and 2 = STRONG:

Now we need to decide how strict the password check should be. I choose Medium (option 1) here, as it is a good compromise between security and usability.

Please set the password for root here.

New password:

Now enter the desired password, taking the requirements into account, and confirm your input. All further prompts should be confirmed with “y”.

Output:

By default, a MySQL installation has an anonymous user,
allowing anyone to log into MySQL 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? (Press y|Y for Yes, any other key for No) : y
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? (Press y|Y for Yes, any other key for No) : y
Success.

By default, MySQL 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? (Press y|Y for Yes, any other key for No) : y
 - 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? (Press y|Y for Yes, any other key for No) : y
Success.

All done!

That is all there is to it. MySQL is now set up on the server. If you want to use phpMyAdmin, you should create a separate user for it. For security reasons, when creating a new user you should only allow connections via localhost. To create the user, we first connect to the database.

sudo mysql

Create a new user:

CREATE USER 'username'@'localhost' IDENTIFIED BY 'deinpw';
GRANT ALL PRIVILEGES ON *.* TO 'phpmyadmin'@'localhost' WITH GRANT OPTION;
FLUSH PRIVILEGES;

You can then use this newly created user, for example for phpMyAdmin, to access the database. Users can also be restricted to specific databases.

Additional Server Security

Fail2Ban

We connect to our server over the internet, which means that others can theoretically do so as well. Especially when using simple “user/password” authentication, attackers can try millions of passwords, for example through brute force, to gain access to the server. If you connect to the server with SSH keys, you already have an advantage, but an additional security layer is always a good idea. Fail2Ban monitors your server’s log files, looks for failed login attempts, and, after a number of failed attempts that you choose, puts the attacker’s IP on a ban list. Attackers then have, for example, only 3 attempts to figure out your password before the ban takes effect and the server rejects all connections from that address. Now the question of course arises whether this is also compatible with the GDPR. In my opinion, the legitimate interest in not being hacked applies here, as does of course the obligation to protect data. The decision for or against Fail2Ban is yours, though. I am unfortunately not the right point of contact for well-founded legal advice.

Nevertheless, here is a quick introduction to Fail2Ban.

Installation:

sudo apt-get install fail2ban

Enable the process at server startup and start Fail2Ban

sudo systemctl start fail2ban
sudo systemctl enable fail2ban

The service should be running now. All we need is a suitable config file, which we create with:

sudo nano /etc/fail2ban/jail.local

We paste the following starter configuration into the file:

[sshd]
enabled = true
port = 22
filter = sshd
logpath = /var/log/auth.log
maxretry = 3

Save the file now and close the editor with CTRL + X. To apply the changes, we restart the service.

sudo systemctl restart fail2ban

From now on, attackers are locked out after three failed login attempts. You can of course try out Fail2Ban yourself now, but before you do, make sure that you have another way of connecting to the server besides SSH.

Removing an IP Address from the Ban List:

To remove an IP address from the ban list, you can use the following command (instead of IP_ADRESSE, you of course need to enter the affected IP address):

sudo fail2ban-client set sshd unbanip IP_ADRESSE

With that, you have configured Fail2Ban at a basic level. You can find out more about using this essential tool on the command line:

man fail2ban

Conclusion

Your server is now ready for use. Especially when it comes to security, there are many ways to protect your server from unauthorized access. As a next step, you can learn about server monitoring, for example. There are also a number of security topics we have not covered in this guide. If you access the internet from a static IP address, it is also advisable to restrict SSH access to your IP address. External requests that do not come from you are then blocked directly. There is always something to learn, and that is a good thing.

Maintenance & Operations

Hand off your server worries?

Updates, backups, and monitoring - so your website runs reliably.

See maintenance
Server2 min

Enable Wake on LAN in Proxmox / Debian

Wake on LAN powers on your server over the network with a magic packet. This guide shows the Linux setup with ethtool under Proxmox and Debian.

Server4 minArchive

Linux Root Server / vServer Monitoring

Your own root server or vServer needs monitoring. An overview of tools like UptimeRobot, htop, Logwatch, NetData and Nagios that alert you when it fails.

New project?

Contact.

Tell me briefly about your project - I'll get back to you personally.

Your data is used solely to handle your inquiry. More in the privacy policy.