How to Install NGINX on Debian & Ubuntu: Server Blocks, HTTPS and Reverse Proxy
When it comes to running a web server for all of my online projects, NGINX is the first that comes to mind for me. By default, it follows my guidelines of running a piece of software – meaning that the software is security-minded, performance-driven, and honestly, really easy to manage all the aspects of it.
NGINX is most likely the most popular web server software in the world, and it's well known for being the backbone of some of the biggest sites on the internet to date. It is a lightweight choice that can be used as either a web server and or reverse proxy, and pretty much fits most people's needs without too much configuration and setup.
In the following guide, I will be walking you through how to install NGINX on Debian-based Linux Distributions (Distros), as well as adding some common firewall rules and setting up a server block for a domain.
Installation
NGINX is usually always available via Debian-based Distros' repositories, so we will be able to install it using the apt package system.
The following command will install NGINX and any required dependencies on the webserver for us.
sudo apt install nginxFirewall Adjustments
Part of making sure our server is secure is by adjusting the firewall. The package which we recommend for this is ufw. The following commands will first see if the firewall is enabled, then allow the required ports to be opened as needed, and finally enable the firewall to run the NGINX web server.
sudo ufw status
sudo ufw allow 22
sudo ufw allow 80
sudo ufw allow 443
sudo ufw enable
sudo ufw statusFirst, we are going to check the status of ufw. It is going to say that the status is `inactive` to begin. Next, we are going to open port 22 for SSH/SFTP traffic, then port 80 for HTTP or normal traffic, and finally port 443 for SSL/TLS or secure web traffic. After the ports are opened, we are going to enable the firewall rules. All other ports will be blocked besides the ones we opened. Finally, we will check the status of the firewall again. The following should be the output.
Status: active
To Action From
-- ------ ----
22 ALLOW Anywhere
80 ALLOW Anywhere
443 ALLOW Anywhere
22 (v6) ALLOW Anywhere (v6)
80 (v6) ALLOW Anywhere (v6)
443 (v6) ALLOW Anywhere (v6)Finalize Installation
At the end of the installation process, your Linux distro will start the NGINX web server. The web server should always be up and running. We are able to check this with the systemd init system. To check if the webserver is running, run the following command.
sudo systemctl status nginx● nginx.service - A high performance web server and a reverse proxy server
Loaded: loaded (/lib/systemd/system/nginx.service; enabled; vendor preset: enabled)
Active: active (running) since Fri 2020-04-20 16:08:19 UTC; 3 days ago
Docs: man:nginx(8)
Main PID: 2369 (nginx)
Tasks: 2 (limit: 1153)
Memory: 3.5M
CGroup: /system.slice/nginx.service
├─2369 nginx: master process /usr/sbin/nginx -g daemon on; master_process on;
└─2380 nginx: worker processThe output right above will confirm that the NGINX web server has started and is currently running. You can access the default NGINX landing page by visiting your website and or IP address that points to the webserver.
Server Block Setup
Server Blocks – pretty similar to Virtual Hosts in Apache's Web Server) – can be used to set up and configure a website on a domain name. The server blocks can also allow you to host multiple websites on the same web server by making their own server blocks for each separate site. I will set up a domain called your_domain, but you should replace this with your own domain name.
NGINX has one server block enabled by default. This block is configured to serve websites out of the directory at /var/www/html. While this works well for a single site, it can become unwieldy if you are hosting multiple sites. Instead of modifying and using the/var/www/html directory, I am going to create a directory structure within the /var/www directory for our your_domain.
sudo mkdir /var/www/your_domain
sudo chown -R $USER:$USER /var/www/your_domain
sudo chmod -R 755 /var/www/your_domainThe following three commands right above will create the directory that is going to house the website. The first command creates the directory folder where you can place public-facing files such as index.html, style.css, and images for a website. The second command assigns ownership to be able to upload, modify, and delete files from the directory as needed. Then the final command sets the correct permissions to allow the owner to read, write, and execute the files while granting only read and execute permissions to groups and others.
In order for Nginx to serve this content, it’s necessary to create a server block with the correct directives. Instead of modifying the default configuration file directly, let’s make a new one at /etc/nginx/sites-available/your_domain.conf.
sudo nano /etc/nginx/sites-available/your_domainNext, I will provide a simple and minimalistic server block that needs to be updated with your domain name which you are using for the server_name and root /var/www/your_domain respectfully.
server {
listen 80;
listen [::]:80;
server_name your_domain;
root /var/www/your_domain/html;
index index.html;
location / {
try_files $uri $uri/ =404;
}
}I think you have noticed how I have updated the root and server_name configuration to our new directory. Next, I will enable the file by creating a link from it to the sites-enabled directory, which Nginx reads from during startup:
sudo ln -s /etc/nginx/sites-available/your_domain /etc/nginx/sites-enabled/If there aren’t any problems, restart Nginx to enable your changes:
sudo systemctl restart nginx
Nginx should now be serving your domain name. You can test this by navigating to https://your_domain. It will be displaying the default NGINX file, 404 error, or a 403 error because there are no found files.
If you're enjoying what you've read so far, we recommend What is a Web Server? Apache, Nginx, and How the Internet Delivers Web Pages as your next read.
Important NGINX Files and Directories
Web Server Content
/var/www/html/: The actual website content directory of a default NGINX installation, which by default only consists of only the default NGINX. The default path is served out of the/var/www/htmldirectory, but this can be changed to whatever you want by changing configuration files.
Server Configuration
/etc/nginx: This is the NGINX installation directory. All of the NGINX application and configuration files are here./etc/nginx/nginx.conf: This is the main NGINX configuration file. This can be modified to make changes to the NGINX application and configuration./etc/nginx/sites-available/: The default directory where different website server blocks should be stored. NGINX will not use the configuration files found in this directory unless they are linked to thesites-enableddirectory by default. Almost all of the time, all server block configuration is done in this directory, and then enabled by linking to thesites-enableddirectory./etc/nginx/sites-enabled/: The directory where different enabled website server blocks are stored. Almost all of the time, these are created by linking to configuration files found in thesites-availabledirectory./etc/nginx/snippets: This directory contains configuration fragments that can be included elsewhere in the NGINX configuration. Potentially repeatable configuration segments are good candidates for reusing in different website configuration files.
Web Server Logs
/var/log/nginx/access.log: Every request made by the webserver is recorded in this log file for reference if needed./var/log/nginx/error.log: Any errors that may happen with NGINX will be recorded in this log. You can reference the errors in the log to solve issues.\
Default Configuration File
##
# You should look at the following URL's in order to grasp a solid understanding
# of Nginx configuration files in order to fully unleash the power of Nginx.
# http://wiki.nginx.org/Pitfalls
# http://wiki.nginx.org/QuickStart
# http://wiki.nginx.org/Configuration
#
# Generally, you will want to move this file somewhere, and start with a clean
# file but keep this around for reference. Or just disable in sites-enabled.
#
# Please see /usr/share/doc/nginx-doc/examples/ for more detailed examples.
##
# Default server configuration
#
server {
listen 80 default_server;
listen [::]:80 default_server;
# SSL configuration
#
# listen 443 ssl default_server;
# listen [::]:443 ssl default_server;
#
# Note: You should disable gzip for SSL traffic.
# See: https://bugs.debian.org/773332
#
# Read up on ssl_ciphers to ensure a secure configuration.
# See: https://bugs.debian.org/765782
#
# Self signed certs generated by the ssl-cert package
# Don't use them in a production server!
#
# include snippets/snakeoil.conf;
root /var/www/html;
# Add index.php to the list if you are using PHP
index index.html index.htm index.nginx-debian.html;
server_name _;
location / {
# First attempt to serve request as file, then
# as directory, then fall back to displaying a 404.
try_files $uri $uri/ =404;
# proxy_pass http://localhost:8080;
# proxy_http_version 1.1;
# proxy_set_header Upgrade $http_upgrade;
# proxy_set_header Connection 'upgrade';
# proxy_set_header Host $host;
# proxy_cache_bypass $http_upgrade;
}
# pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
#
#location ~ \.php$ {
# include snippets/fastcgi-php.conf;
#
# # With php7.0-cgi alone:
# fastcgi_pass 127.0.0.1:9000;
# # With php7.0-fpm:
# fastcgi_pass unix:/run/php/php7.0-fpm.sock;
#}
# deny access to .htaccess files, if Apache's document root
# concurs with nginx's one
#
#location ~ /\.ht {
# deny all;
#}
}
# Virtual Host configuration for example.com
#
# You can move that to a different file under sites-available/ and symlink that
# to sites-enabled/ to enable it.
#
#server {
# listen 80;
# listen [::]:80;
#
# server_name example.com;
#
# root /var/www/example.com;
# index index.html;
#
# location / {
# try_files $uri $uri/ =404;
# }Free HTTPS with Let's Encrypt and Certbot
Installing CertBot
The first main step is to install the CertBot application to obtain a valid SSL/TSL Certificate for your web server. The following command will install CertBot with its NGINX plugin using the apt package manager.
sudo apt install certbot python3-certbot-nginxOnce the installation is complete, the CertBot application is ready to use. Now we need to configure a few things on NGINX's side to get the CertBot application to work.
General Configuration
CertBot will need to find the right path to the correct server block in our NGINX configuration so that it can automatically set up and configure SSL/TLS for us. To accomplish this, CertBot will search for a server_name directive in your config that matches the domain we will request the certificate for.
Please Note: If you followed our guide for server block set up, you should already have a server block for your domain at /etc/nginx/sites-available/example.com with the server_name directive already set accordingly.
To check if you have this setup properly, we will open the configuration file for your domain using nano package or your favorite text editor.
sudo nano /etc/nginx/sites-available/example.comYou will need to find the existing server_name block.
...
...
server_name example.com;
...
...If this line is already created with your domain name in it, we are done with this step. If this line is not set up or configured, then you will need to make it in your configuration file inside the correct server block. Then you will save the file, quit the editor, then verify the syntax to make sure the configuration file is correct.
sudo nginx -tIf you get an error, then you will have to reopen the configuration file for your domain. This will allow you to fix any typos or missing characters that could be causing the error.
Finally, we are going to restart NGINX to apply the changes we made to the configuration files.
sudo systemctl reload nginxObtaining an SSL Certificate
CertBot provides our SSL Certificates which we want for our website. There is a variety of ways to obtain one through different plugins. The NGINX plugin will take care of most of the hard work of configuring NGINX and reloading the configuration whenever it's needed. To use the plugin, we are going to run the following command.
sudo certbot --nginx -d example.com -d www.example.comThis command runs the certbot application with the --nginx plugin. We also have to have the -d tag to specify the domain for which we want to make the SSL Certificate.
If this is the first time you are using CertBot on your machine, then you will be prompted to enter an email address to receive notifications and agree to the terms of service. Then, it will ask if you want it to automatically setup and create a redirection to https:// version of your website. Here's what the redirection prompt looks like at the time of writing:
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):After that, CertBot will finish up anything else it needs to do to generate your certificates. Once CertBot has completed, a message will appear stating it was successful and where the certificates were stored. The message looks like the following at the time of writing:
IMPORTANT NOTES:
- Congratulations! Your certificate and chain have been saved at:
/etc/letsencrypt/live/example.com/fullchain.pem
Your key file has been saved at:
/etc/letsencrypt/live/example.com/privkey.pem
Your cert will expire on 2021-08-18. 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"
- 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-leYour certificates are now officially downloaded, installed, and loaded. Now you can try reloading your website using https:// and notice your browser’s security indicator. It should indicate that the site is properly secured, usually with a lock icon. If you test your server using the SSL Labs Server Test, it will get an A grade.
Setting Up NGINX as a Reverse Proxy
Creating the Configuration File
First, we are going to create the NGINX configuration file for your first website you want to run using Ghost Blog as our example web application of choice. Make sure to change example.conf to your own domain that you want to use.
sudo nano /etc/nginx/sites-available/example.confThe following is a generalized configuration file that is a bare minimal setup for running Ghost as your web application of choice. The first server block sets up our redirection to the https:// version of our domain and does a 301 permanent redirection for all incoming traffic. We also chosen to listen on IPv4 and IPv6.
server {
listen 80;
listen [::]:80;
# Redirection Configuration
server_name example.com;
return 301 https://example.com;
}SSL Configuration
Next we will open up a second server block like the following. It is for all traffic that is going to be connecting via our SSL or https://` connection once the redirect has been performed.
server {
listen 443 http2 ssl;
listen [::]:443 http2 ssl;Next, in my configuration files once we setup the listening ports, I like to do the SSL configuration. This is where our LetsEncrypt certificates come into place. The options-ssl-nginx.conf; is recommended SSL security settings that make our site a little more secure by default. Finally, the LetsEncrypt generates us a Diffie-Hellman (DH) parameters file which is ssl-dhparams.pem in our SSL configuration.
It enhances the security of Perfect Forward Secrecy (PFS) in SSL/TLS by explicitly providing strong DH parameters instead of relying on weak, default ones. These parameters are used in the Diffie-Hellman key exchange algorithm to negotiate a secure session key between the server and client.
# SSL Configuration
ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
include /etc/letsencrypt/options-ssl-nginx.conf;
ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem;General Configuration
Now we have the General Settings part of our website configuration It sets our server_name, root directory, index, and other settings as needed. Since we are proxying Ghost Blog, we can comment out the root and index lines. The final two lines deals with uploading files like themes or pictures you can use with the blog. By default, we allow 100MB files and 3 minutes for the upload to complete. You can adjust these as needed, but the ones we use here are recommended.
# General Configuration
server_name example.com;
#root /var/www/html;
#index index.php index.html;
client_max_body_size 100m;
client_body_timeout 120s;Reverse Proxy Configuration
The final part of our configuration file is for the / or root of where the site is going to be installed. Here at SudoSecurity, we have the blog installed on the main domain, https://sudosecurity.org/. You could even do a sub-domain like blog.example.com if you prefer for your own site. The choice is yours at the end of the day.
The location block tells the webserver to run the application in the root folder of /. You could also make it a dub-directory such as /blog/ if you wanted too. These headers ensure your backend app receives correct information about the original client request (IP, Protocol, and Domain), which is essential for accurate behavior and logging behind a reverse proxy.
# Ghost Blog
location / {
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header Host $http_host;
proxy_pass http://127.0.0.1:2368;
}
}Checking Configuation
Finally, we want to run the following commands. The first one creates a symbolic link to sites-enabled directory for the site to be alive. The second line will check for any errors with your NGINX configuration. Then at last, we will reload NGINX for the changes to take effect. Please remember when you make any changes to any NGINX or site configuration files, you always need to reload NGINX for the changes you make to take effect.
sudo ln -s /etc/nginx/sites-available/example.conf /etc/nginx/sites-enabled/
sudo nginx -t
sudo systemctl reload nginxThe Conclusion
Now that the webserver is officially installed, you have many options for the type of content to serve to the public. There are a lot of different technologies that we can use to create an amazing user experience for people who visit our website.
$ tail -f /forums
Discussion
Comments live on the community forums — sign in there to reply.