How to setup a webserver with NGINX

This guide will show you how to setup an NGINX web server, open to the public.

First, connect to your server via SSH.

Next, type sudo apt install nginx. This will install the nginx package, which is a webserver.

Once NGINX is installed on your server, go into your browser and type your server's IP address. Once done, you should be met with a screen like this:

If you would like to use a domain and HTTPS, follow these steps.

First, you need to point a domain to your server's IP address with an A record, like below.

Then, type sudo apt install certbot. This will allow us to create an SSL certificate, enabling HTTPS on the server.

Once cerbot is installed, type sudo apt install python3-certbot-nginx. This is an addon for certbot, for NGINX.

Once both of the packages are installed on your server, type sudo certbot certonly --nginx -d example.com. Replacing example.com with your domain. Next, input your email address as it asks, it is used to send updates when your SSL Certificate is about to expire. Next, type Y to agree to the ToS. Next, you will be asked to share your email, you can type Y or N.

Once the above is finished, you should see something like below, meaning that you have successfully gained an SSL Certificate, which will automatically renew itself.

Next, remove the old NGINX configuration with sudo rm /etc/nginx/sites-available/default and make a new one with sudo nano /etc/nginx/sites-available/default. Then, in that file, put the following:

server {
    listen 80;
    server_name <your-domain-here>;
    return 301 https://$server_name$request_uri;
}

server {

	listen 443 ssl http2;
        server_name <your-domain-here>;

	
        ssl_certificate /etc/letsencrypt/live/<your-domain-here>/fullchain.pem;
        ssl_certificate_key /etc/letsencrypt/<your-domain-here>/privkey.pem;
        ssl_session_cache shared:SSL:10m;
        ssl_protocols TLSv1.2 TLSv1.3;
        ssl_ciphers "ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384";
        ssl_prefer_server_ciphers on;

	root /var/www/html;

	# Add index.php to the list if you are using PHP
	index index.html index.htm index.nginx-debian.html;

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

}

And replace all of the <your-domain-here> with your domain or subdomain. This configuration allows your site to be hosted with an SSL Certificate, and be on the HTTPS port, and HTTP port. If your website gets a request from HTTP, it will be redirected to HTTPS.

Once you have put this configuration on your server, type sudo systemctl restart nginx to restart NGINX and apply the new configuration. Now, your server is on HTTPS with an SSL Certificate!

Your website files are now stored in /var/www/html. You can add files, remove, edit, etc.

Last updated