Skip to content
lanzai.co
Go back

Installing Nginx and Basic Configuration

Nginx is a high-performance web server and reverse proxy.

Install

sudo apt update
sudo apt install -y nginx
sudo systemctl enable --now nginx
nginx -v

Allow it through the firewall:

sudo ufw allow 'Nginx Full'

Directory layout

/etc/nginx/
├── nginx.conf        # main config
├── sites-available/  # site configs (before enabling)
└── sites-enabled/    # enabled sites (symlinks)

Add a site

/etc/nginx/sites-available/blog.conf:

server {
    listen 80;
    server_name blog.example.com;

    root /var/www/blog;
    index index.html;

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

Enable and reload:

sudo ln -s /etc/nginx/sites-available/blog.conf /etc/nginx/sites-enabled/
sudo nginx -t          # test config
sudo systemctl reload nginx

Reverse proxy to a local service

server {
    listen 80;
    server_name app.example.com;

    location / {
        proxy_pass http://127.0.0.1:8080;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }
}

HTTPS with certbot

sudo apt install -y certbot python3-certbot-nginx
sudo certbot --nginx -d blog.example.com
# auto-renewal is handled by certbot renew

Common operations

sudo systemctl status nginx      # status
sudo nginx -t                    # test config
sudo tail -f /var/log/nginx/error.log

Share this post:

Previous Post
Docker Commands Cheat Sheet
Next Post
Linux Server Troubleshooting