Mastering Nginx: Installation, Reverse Proxy, Load Balancing, and CORS Setup
This guide explains what Nginx is, how to install it on Linux and Windows, compile from source, use common control commands, and configure HTTP/HTTPS reverse proxy, load balancing, multiple web‑app routing, static site serving, and CORS handling with practical code examples.
What is Nginx?
Nginx (engine x) is a lightweight web server, reverse‑proxy server, and mail (IMAP/POP3) proxy.
What is a reverse proxy?
A reverse proxy receives client requests from the Internet, forwards them to internal servers, and returns the responses to the clients, appearing as a single front‑end server.
Installation
Binary packages
Download the official Linux or Windows binaries from http://nginx.org and unpack them.
Compile from source (Linux/macOS)
$ ./configure
$ make
$ sudo make installBy default Nginx installs to /usr/local/nginx. Use ./configure --prefix=/your/path to change the installation directory.
Windows installation
cd C:\
cd C:
ginx-1.24.0
start nginxOn Windows the Win32 package runs as a console program; it is not installed as a Windows service by default.
Common control commands
nginx -s stop– fast stop without graceful shutdown. nginx -s quit – graceful shutdown, saving state. nginx -s reload – reload configuration after changes. nginx -s reopen – reopen log files. nginx -c /path/to/nginx.conf – use a specific configuration file. nginx -t – test configuration syntax only. nginx -v – display version. nginx -V – display version, compiler, and configure parameters.
A simple batch file ( startup.bat) can automate these commands on Windows:
@echo off
rem stop if already running
nginx.exe -s stop
rem test configuration syntax
nginx.exe -t -c conf
ginx.conf
rem show version
nginx.exe -v
rem start with specified config
nginx.exe -c conf
ginx.confConfiguration examples
1. Basic HTTP reverse proxy
A minimal nginx.conf that forwards all traffic to an upstream server and serves static assets directly:
#worker_processes 1;
error_log logs/error.log;
pid logs/nginx.pid;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
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 logs/access.log main;
sendfile on;
keepalive_timeout 120;
tcp_nodelay on;
upstream backend {
server 127.0.0.1:8089;
}
server {
listen 80;
server_name www.example.com;
root /var/www/html;
index index.html;
# Reverse‑proxy all requests
location / {
proxy_pass http://backend;
}
# Serve static assets directly
location ~ ^/(images|js|css|media)/ {
root /var/www/static;
expires 30d;
}
# Status page (optional)
location /nginx_status {
stub_status on;
allow 127.0.0.1;
deny all;
}
# Protect hidden files
location ~ /\.ht {
deny all;
}
}
}2. Load‑balancing across multiple back‑ends
Distribute traffic among three backend servers with weighted round‑robin:
http {
include mime.types;
default_type application/octet-stream;
access_log /var/log/nginx/access.log;
upstream load_balance {
server 192.168.1.11:80 weight=5;
server 192.168.1.12:80 weight=1;
server 192.168.1.13:80 weight=6;
}
server {
listen 80;
server_name www.example.com;
location / {
proxy_pass http://load_balance;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_connect_timeout 90;
proxy_send_timeout 90;
proxy_read_timeout 90;
proxy_buffer_size 4k;
proxy_buffers 4 32k;
proxy_busy_buffers_size 64k;
client_max_body_size 10m;
client_body_buffer_size 128k;
}
}
}3. Routing multiple web‑apps under different URL prefixes
Each application runs on a distinct port; Nginx routes based on the request path:
http {
upstream product { server www.example.com:8081; }
upstream admin { server www.example.com:8082; }
upstream finance { server www.example.com:8083; }
server {
listen 80;
server_name www.example.com;
location /product/ { proxy_pass http://product; }
location /admin/ { proxy_pass http://admin; }
location /finance/ { proxy_pass http://finance; }
# Default fallback (optional)
location / { proxy_pass http://product; }
}
}4. Serving a static site
Serve a pre‑built SPA from /app/dist and enable gzip compression:
worker_processes 1;
events { worker_connections 1024; }
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
keepalive_timeout 65;
gzip on;
gzip_types text/plain application/javascript text/css image/jpeg image/gif image/png;
gzip_vary on;
server {
listen 80;
server_name static.example.com;
location / {
root /app/dist;
index index.html;
# Fallback to index.html for SPA routing
try_files $uri $uri/ /index.html;
}
}
}5. HTTPS reverse proxy
Enable TLS on port 443 with a certificate and key. The example uses self‑signed files cert.pem and cert.key:
server {
listen 443 ssl;
server_name www.example.com;
ssl_certificate cert.pem;
ssl_certificate_key cert.key;
ssl_session_cache shared:SSL:1m;
ssl_session_timeout 5m;
ssl_ciphers HIGH:!aNULL:!MD5;
ssl_prefer_server_ciphers on;
location / {
proxy_pass http://backend;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}6. CORS (Cross‑Origin Resource Sharing) configuration
A reusable snippet ( enable-cors.conf) that can be included for API locations:
# Allow all origins by default
set $ACAO '*';
# Restrict to a specific origin if needed
if ($http_origin ~* (www.example.com)$) {
set $ACAO $http_origin;
}
# Build a flag based on request method
set $cors "";
if ($request_method = 'OPTIONS') { set $cors "${cors}options"; }
if ($request_method = 'GET') { set $cors "${cors}get"; }
if ($request_method = 'POST') { set $cors "${cors}post"; }
# Add CORS headers when the flag is set
if ($cors ~* "(get|post|options)") {
add_header 'Access-Control-Allow-Origin' "$ACAO";
add_header 'Access-Control-Allow-Credentials' 'true';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';
}Include the snippet in an API location and rewrite the request path if necessary:
server {
listen 80;
server_name www.example.com;
location ~ ^/api/ {
include enable-cors.conf;
proxy_pass http://api_backend;
rewrite "^/api/(.*)$" /$1 break;
}
location / {
proxy_pass http://frontend;
}
}Source: www.cnblogs.com/jingmoxukong/p/5945200.htm
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
ITPUB
Official ITPUB account sharing technical insights, community news, and exciting events.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
