Skip to content

Basics of Nginx for Frontend Developers

Nginx is a high-performance, open-source web server that frontend developers often interact with for serving web applications and static assets.

It’s known for its efficiency, low memory footprint, and ability to handle high concurrency.

For frontend development, Nginx is primarily used in two ways:

  1. Serving Static Files: Delivering your HTML, CSS, JavaScript, images, and other static assets directly to the user’s browser.
  2. Reverse Proxy: Routing client requests to different backend services or local development servers.

Basic Syntax

Server block (Virtual Host)

Server block defines how Nginx handles requests for a specific domain or IP.

Think of it like a virtual host — each server block corresponds to one website, app, or API.

If your Nginx config is a book, each server block is a chapter dedicated to one domain.

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

    location / {
        # Configuration for handling requests
    }
}

Basic Server directives

listen 80;                          # Port to listen on
listen 443 ssl;                     # SSL port
server_name example.com;            # Domain name
root /var/www/html;                 # Document root
index index.html index.php;         # Default index files
error_log /var/log/nginx/error.log; # Error log path
access_log /var/log/nginx/access.log; # Access log path

Redirect http to https

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

Location block

Nginx File Locations

# The main entry point for Nginx configuration
/etc/nginx/nginx.conf

# Individual site configurations (virtual hosts)
/etc/nginx/sites-available/

# Contains symlinks to files in sites-available/
/etc/nginx/sites-enabled/

# Logs by default
/var/log/nginx/access.log
/var/log/nginx/error.log

Example: Serve Static App

server {
    listen 80;
    server_name yourdomain.com;

    location / {
        root /var/www/my-app/build;
        index index.html;
        try_files $uri $uri/ /index.html; # Essential for Single Page Applications (SPAs)
    }
}

Example: Reverse Proxy

server {
    listen 80;
    server_name localhost;

    location /api/ {
        # Forward any request to /api/ to the backend running on port 8080
        proxy_pass http://localhost:8080/;

        # You may need to add headers for the backend to work correctly
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
    }

    location / {
        # Serve the local development frontend server running on port 3000
        proxy_pass http://localhost:3000;
    }
}

Basic Commands

sudo apt-get update
sudo apt-get install nginx
nginx -v
sudo service nginx start
sudo service nginx stop
sudo service nginx restart
sudo systemctl reload nginx
sudo nginx -t