Skip to main content

Nginx Cheatsheet

Configuration files

  • /etc/nginx/nginx.conf
  • /etc/nginx/sites-available/*
  • /etc/nginx/sites-enabled/*

Master and worker processes

  • master process reads and evaluate configurations, and maintain worker processes.
  • worker processes process the actual requests
  • number of worker processes can be configured
# start stop restart status
$ sudo service nginx start
$ sudo service nginx stop
$ sudo service nginx restart

$ systemctl status nginx

# check nginx configuration for syntax errors
$ sudo nginx -t

$ nginx -s stop
$ nginx -s reload
$ nginx -s reopen
$ nginx -s quit

Basic server block structure

server {
  listen 80;
  server_name example.com www.example.com;
  location / {
    # other configurations
  }
}

Redirect HTTP to HTTPS

server {
  listen 80;
  server_name example.com
  return 301 https://$host$request_uri;
}

Root Directive

server {
  ...
  location / {
    root /path/to/your/files;
    index index.html;
  }
  ...
}

Proxy Pass

server {
  ...
  location /app {
    proxy_pass http://backend_server;
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
  }
  ...
}

URL Rewriting

server {
  ...
  location /blog {
    # removes "/blog" in url
    rewrite ^/blog/(.*)$ /$1 break;
  }
  ...
}

SSL Configuration

server {
  listen 443 ssl;
  server_name example.com;
  ...
  ssl_certificate /path/to/your/certificate.crt;
  ssl_certificate_key /path/to/your-private.key;
  ...
}

Load Balancing

upstream backend {
  server backend1.example.com
  server backend2.example.com
}

server {
  ...
  location / {
    proxy_pass http://backend;
  }
}