DEV Community

Manthan Ankolekar
Manthan Ankolekar

Posted on

NGINX Cheatsheet: A Quick Reference Guide

NGINX is a powerful and versatile web server that is widely used to serve static content, reverse proxy, and load balance across servers. Whether you're a beginner or an experienced user, having a cheatsheet handy can save time and help you navigate NGINX configurations efficiently. Let's dive into a quick reference guide for NGINX.

Installation and Basic Commands

Installation

sudo apt-get update
sudo apt-get install nginx
Enter fullscreen mode Exit fullscreen mode

Start/Stop/Restart NGINX

sudo service nginx start
sudo service nginx stop
sudo service nginx restart
Enter fullscreen mode Exit fullscreen mode

Check NGINX Configuration

nginx -t
Enter fullscreen mode Exit fullscreen mode

Configuration File Locations

  • Main configuration file: /etc/nginx/nginx.conf
  • Server block configuration: /etc/nginx/sites-available/
  • Enabled server block symlink: /etc/nginx/sites-enabled/

Server Blocks

Basic Server Block Structure

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

    location / {
        # Configuration for handling requests
    }
}
Enter fullscreen mode Exit fullscreen mode

Redirect HTTP to HTTPS

server {
    listen 80;
    server_name example.com www.example.com;
    return 301 https://$host$request_uri;
}
Enter fullscreen mode Exit fullscreen mode

Locations and Directives

Root Directive

location / {
    root /path/to/your/files;
    index index.html;
}
Enter fullscreen mode Exit fullscreen mode

Proxy Pass

location /app {
    proxy_pass http://backend_server;
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
}
Enter fullscreen mode Exit fullscreen mode

URL Rewriting

location /blog {
    rewrite ^/blog/(.*)$ /$1 break;
}
Enter fullscreen mode Exit fullscreen mode

SSL Configuration

SSL Certificate

ssl_certificate /path/to/your/certificate.crt;
ssl_certificate_key /path/to/your/private.key;
Enter fullscreen mode Exit fullscreen mode

Enable SSL

server {
    listen 443 ssl;
    server_name example.com;

    # SSL configuration here
}
Enter fullscreen mode Exit fullscreen mode

SSL Redirect

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

Load Balancing

Round Robin Load Balancing

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

server {
    location / {
        proxy_pass http://backend;
    }
}
Enter fullscreen mode Exit fullscreen mode

This cheatsheet covers essential NGINX configurations, but remember to consult the official documentation for more in-depth details. NGINX's flexibility allows it to be used in various scenarios, making it a crucial tool for web server management.

Top comments (0)