Setup Nginx on Ubuntu for Static Website

Install

Install nginx

sudo apt install nginx

or

sudo apt-get install nginx

NOTE: apt vs apt-get

Check status

systemctl status nginx

Allow Firewall

Check firewall application list.

sudo ufw app list
Available applications:  Nginx Full  Nginx HTTP  Nginx HTTPS  OpenSSH

Allow nginx in firewall (both HTTP and HTTPS)

sudo ufw allow 'Nginx Full'

Check status

sudo ufw status

Nginx Configuration

Edit nginx configuration.

cd /etc/nginx/sites-availablesudo nano NGINX_CONFIG_FILE
server {
  listen 80;
  listen [::]:80;

  root /var/www/MY_HTML_DIRECTORY;

  server_name WWW.MYDOMAIN.COM;


  location / {
    # First attempt to serve request as file, then
    # as directory, then fall back to displaying a 404.
    try_files $uri $uri/ =404;
  }

  # gzip
  gzip on;
  gzip_disable "msie6";
  # only gzip if file size >= 256
  gzip_min_length 256;
  # gzip javascript, css, text (include html as well)
  gzip_types text/plain application/javascript text/css;

  # enable client-side caching by file extension
  location ~* \.(js|css|png|jpg|jpeg|gif|ico)$ {
    expires 1y;
    add_header Cache-Control public;
    access_log off;
  }

  # enable client-side caching by directory
  location ~ ^/(static|img|css|js)/ {
    expires 1y;
    add_header Cache-Control public;
    access_log off;
  }
}

NOTE: You can put your website in other directory besides /var/www/*.

Link site-enabled to sites-available.

cd ../sites-enabledln -s ../sites-available/NGINX_CONFIG_FILE

Reload nginx

sudo nginx -s reload

Enable SSL

Easiet way is to use let's encrypt, which not only get you an SSL certificates which automatically renew, it also automatically setup nginx's ssl configuration.

Enable HTTP/2

After setup SSL, edit NGINX_CONFIG_FILE.

server {
    listen [::]:443 ssl http2; # managed by Certbot
    listen 443 ssl http2; # managed by Certbot
}

Reload nginx

sudo nginx -s reload

NOTE: HTTP/2 allows browsers to request files in parallel, and only works with SSL.

❤️ Is this article helpful?

Buy me a coffee ☕ or support my work via PayPal to keep this space 🖖 and ad-free.

Do send some 💖 to @d_luaz or share this article.

✨ By Desmond Lua

A dream boy who enjoys making apps, travelling and making youtube videos. Follow me on @d_luaz

👶 Apps I built

Travelopy - discover travel places in Malaysia, Singapore, Taiwan, Japan.