Master Nginx: From Static Server to Load Balancing and Reverse Proxy

This guide walks through configuring Nginx as a static file server, explains location directives and regex patterns, shows how to set up reverse proxying, explores various load‑balancing strategies, demonstrates dynamic‑static separation, and covers useful directives such as return, rewrite, error_page, logging and access control.

Open Source Linux
Open Source Linux
Open Source Linux
Master Nginx: From Static Server to Load Balancing and Reverse Proxy

1. HTTP Server

Nginx can serve static resources; when a site only has static pages, you can deploy it directly.

1. Create a Docroot(/usr/local/var/www) directory and an html subdirectory, then place a test.html file.

2. Configure nginx.conf server block:

user mengday staff;
http {
    server {
        listen 80;
        server_name localhost;
        client_max_body_size 1024M;
        # default location
        location / {
            root /usr/local/var/www/html;
            index index.html index.htm;
        }
    }
}

3. Test access: http://localhost/ points to /usr/local/var/www/index.html (default Nginx index). http://localhost/test.html points to /usr/local/var/www/html/test.html.

Note: If you get 403 Forbidden for images, adjust the user directive in nginx.conf (e.g., set to root on Linux or your username on macOS) and reload.

4. Directive summary: server: defines a virtual server; multiple server blocks can exist. listen: IP address and port to listen on. server_name: domain name. location: maps URI patterns to configuration blocks. root: file system path for a location. index: default file when a directory is requested.

5. Location regex examples: .: any character except newline ?: 0 or 1 times +: 1 or more times *: 0 or more times \d: digit ^: start of string $: end of string {n}: exactly n times {n,}: n or more times [c]: character c [a-z]: any lowercase letter (a|b|c): alternation \: escape special characters

2. Static Server

In many companies a static server provides uploaded assets for other applications.

1. Under /usr/local/var/www create images and img directories and place a test.jpg in each.

http {
    server {
        listen 80;
        server_name localhost;

        set $doc_root /usr/local/var/www;

        # default location
        location / {
            root $doc_root/html;
            index index.html index.htm;
        }

        location ^~ /images/ {
            root $doc_root;
        }

        location ~* \.(gif|jpg|jpeg|png|bmp|ico|swf|css|js)$ {
            root $doc_root/img;
        }
    }
}

Custom variable set defines $doc_root. Two mapping methods for static resources: path‑based ( /images/) and suffix‑based (file extensions).

Accessing http://localhost/test.jpg maps to $doc_root/img. When multiple locations match, ^~ has higher priority than ~, so the /images/ block is chosen.

Common location matching types (from highest to lowest priority): =: exact match ^~: prefix match, stop searching ~ and ~*: regex match (case‑sensitive / insensitive)

regular string prefix /: catch‑all

Location priority

Priority depends on the expression type, not the order in the file. Same‑type expressions prefer the longer string.

location = / {
    # exact match
    [configuration A]
}
location / {
    # matches any URI starting with /
    [configuration B]
}
location /documents/ {
    # matches prefix /documents/
    [configuration C]
}
location ^~ /images/ {
    # high‑priority prefix
    [configuration D]
}
location ~* \.(gif|jpg|jpeg)$ {
    # regex match
    [configuration E]
}

Note: location priority is independent of its position in the file.

3. Reverse Proxy

Reverse proxy forwards client requests to internal servers and returns the response. It is implemented with the proxy_pass directive.

Example: a Java web app listening on port 8081.

server {
    listen 80;
    server_name localhost;

    location / {
        proxy_pass http://localhost:8081;
        proxy_set_header Host $host:$server_port;
        proxy_set_header X-Forwarded-For $remote_addr;
        proxy_next_upstream error timeout invalid_header http_500 http_502 http_503;
    }
}

Visiting http://localhost/ proxies to http://localhost:8081.

4. Load Balancing

Load balancing distributes requests across multiple backend servers. Nginx uses the upstream block.

1. Round Robin (default)

Requests are sent to servers in order.

upstream web_servers {
    server localhost:8081;
    server localhost:8082;
}
server {
    listen 80;
    server_name localhost;
    location / {
        proxy_pass http://web_servers;
        proxy_set_header Host $host:$server_port;
    }
}

2. Weighted

upstream test {
    server localhost:8081 weight=1;
    server localhost:8082 weight=3;
    server localhost:8083 weight=4 backup;
}

Weight determines the proportion of requests each server receives; backup is used only when all primary servers fail.

3. ip_hash

Ensures the same client IP always reaches the same backend, useful for session‑affinity.

upstream test {
    ip_hash;
    server localhost:8080;
    server localhost:8081;
}

4. fair (third‑party)

Distributes based on response time; requires the third‑party fair module.

upstream backend {
    fair;
    server localhost:8080;
    server localhost:8081;
}

5. url_hash (third‑party)

Hashes the request URI; useful for caching. Requires the hash module.

upstream backend {
    hash $request_uri;
    hash_method crc32;
    server localhost:8080;
    server localhost:8081;
}

Choose the strategy that fits your scenario; third‑party modules are required for fair and url_hash.

5. Dynamic‑Static Separation

Separate dynamic and static resources so static files can be cached.

upstream web_servers {
    server localhost:8081;
    server localhost:8082;
}
server {
    listen 80;
    server_name localhost;

    set $doc_root /usr/local/var/www;

    location ~* \.(gif|jpg|jpeg|png|bmp|ico|swf|css|js)$ {
        root $doc_root/img;
    }

    location / {
        proxy_pass http://web_servers;
        proxy_set_header Host $host:$server_port;
    }

    error_page 500 502 503 504 /50x.html;
    location = /50x.html {
        root $doc_root;
    }
}

6. Other Directives

return

Returns an HTTP status code and optional URL.

location /permanently/moved/url {
    return 301 http://www.example.com/moved/here;
}

rewrite

Modifies the request URI using a regular expression.

location /users/ {
    rewrite ^/users/(.*)$ /show?user=$1 break;
}

error_page

Defines custom error pages.

error_page 404 /404.html;

log_format & access_log

Configure request logging (enable gzip on to generate logs).

log_format main '$remote_addr - $remote_user [$time_local] "$request" '
                '$status $body_bytes_sent "$http_referer" '
                '"$http_user_agent" "$http_x_forwarded_for"';
access_log /usr/local/etc/nginx/logs/host.access.log main;
gzip on;

deny

Block access to matching files.

location ~* \.(txt|doc)$ {
    root $doc_root;
    deny all;
}

Built‑in variables

Common Nginx variables such as $args, $content_length, $host, $remote_addr, $request_uri, etc., can be used in configurations.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

load balancingConfigurationNginxreverse proxyWeb serverStatic files
Open Source Linux
Written by

Open Source Linux

Focused on sharing Linux/Unix content, covering fundamentals, system development, network programming, automation/operations, cloud computing, and related professional knowledge.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.