---
title: nginx Cheat Sheet
description: nginx Cheat Sheet for VPS setup
tokens: ~645
---

# nginx Cheat Sheet

We usually put nginx in front of the application because it acts as the public entry point to the server. 
It handles HTTPS, domains, redirects, static files, and request routing, while the application can safely run behind it on a local port.

This note is a short cheat sheet for nginx on VPS setup.

## Install and run

```bash
sudo apt install nginx
sudo service nginx start
```

### View default nginx config:

```bash
sudo cat /etc/nginx/sites-available/default
```

### Check config and control the service:

```bash
sudo nginx -t                    # nginx config syntax check (before reload)
sudo systemctl reload nginx      # reload nginx (workers pick up changes)
sudo systemctl restart nginx     # restart nginx (brief disconnect for clients)
```

By default, nginx serves static files from `/var/www/html`.

### Change ownership of /var/www

To change the ownership of `/var/www/html` to the new user, run:

```bash
sudo chown -R $USER:$USER /var/www
```

Now you can create and edit files inside `/var/www` without using `sudo` every time.

### Create a new nginx site

nginx site configs are usually stored in `/etc/nginx/sites-available`.

Enabled sites are linked from `/etc/nginx/sites-enabled`.

Create a new config:

```bash
sudo vi /etc/nginx/sites-available/my-site
```

```bash
server {
    listen 80;
    server_name example.com www.example.com;

    root /var/www/my-site;
    index index.html;

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

Enable the site by creating a symlink:

```bash
sudo ln -s /etc/nginx/sites-available/my-site /etc/nginx/sites-enabled/my-site
```

Then check and reload nginx: `sudo nginx -t` and `sudo systemctl reload nginx`.

### Proxy requests to an app

A common setup is to run your app on a local port, for example, `localhost:3000`
Then nginx receives public traffic on port `80` or `443` and forwards it to the app.

Example config:

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

    server_name example.com www.example.com;

    location / {
        proxy_pass http://localhost:3000;
    }
}
```


In this setup:

```text
Browser → nginx → app running on localhost:3000
```

The app does not need to be exposed directly to the internet.

### Useful paths

```bash
/etc/nginx/nginx.conf              # main nginx config
/etc/nginx/sites-available         # available site configs
/etc/nginx/sites-enabled           # enabled site configs
/var/www/html                      # default web root
/var/log/nginx/access.log          # access logs
/var/log/nginx/error.log           # error logs
```