Master Nginx on CentOS: Installation, Configuration, Reverse Proxy, Load Balancing and HTTPS
This comprehensive guide walks you through installing Nginx on CentOS 7.6, explains core concepts such as simple vs non‑simple requests, CORS, forward and reverse proxies, then shows step‑by‑step configurations for virtual hosts, reverse proxying, gzip compression, load balancing, high‑availability with keepalived, device‑specific routing, HTTPS setup and dozens of practical tricks for production environments.
1. Introduction
Developers increasingly need reverse‑proxy capabilities when building blogs or web services. Nginx is a high‑performance, open‑source web and reverse‑proxy server that can run 24/7 without restarts, making it essential for modern deployments.
2. Nginx Overview
Traditional web servers spawn a new process or thread per connection, consuming extra CPU and memory. Nginx uses an event‑driven architecture, handling thousands of concurrent connections with minimal resources.
Typical use cases include static file serving, reverse proxy (with caching and load balancing), and API services via OpenResty.
2.1 Simple vs Non‑Simple Requests
A request is considered simple when it uses GET, POST or HEAD and only the headers Accept, Accept‑Language, Content‑Language, Last‑Event‑ID and one of the three content‑type values. Otherwise it is a non‑simple request, which triggers a pre‑flight OPTIONS request.
2.2 Cross‑Origin (CORS)
Browsers enforce the same‑origin policy. CORS headers such as Access‑Control‑Allow‑Origin allow a server to relax this restriction.
2.3 Forward vs Reverse Proxy
Forward proxy hides the client from the target server; reverse proxy hides the server from the client and forwards requests to internal services. Reverse proxy is the common solution for load balancing and CORS handling.
2.4 Load Balancing
When traffic spikes, a single server becomes a bottleneck. Distributing requests across multiple back‑ends (e.g., via Nginx upstream) balances the load.
2.5 Static/Dynamic Separation
Serving static assets directly from Nginx while proxying dynamic requests to an application server reduces server load and improves response time.
3. Installation on CentOS 7.6
yum list | grep nginx
yum install nginx
nginx -v # verify version
rpm -ql nginx # list installed filesKey directories: /etc/nginx/conf.d/ – sub‑configuration files /etc/nginx/nginx.conf – main configuration /usr/share/nginx/html/ – default static root
3.3 Service Management
# Firewall (optional)
systemctl start firewalld
firewall-cmd --permanent --add-port=80/tcp
firewall-cmd --reload
# Enable and start Nginx
systemctl enable nginx
systemctl start nginx4. Common Nginx Commands
nginx -s reload # reload configuration
nginx -s stop # fast shutdown
nginx -t -c /path/to/nginx.conf # test config
systemctl restart nginx # restart via systemd5. Configuration Syntax
The main file /etc/nginx/nginx.conf is organized as main → events → http → upstream / server / location. Directives end with ;, blocks use {}, comments start with #, and variables are prefixed with $.
5.1 Typical Configuration Example
user nginx;
worker_processes 1;
error_log /var/log/nginx/error.log warn;
pid /var/run/nginx.pid;
events {
use epoll;
worker_connections 1024;
}
http {
log_format main '$remote_addr - $remote_user [$time_local] "$request" $status $body_bytes_sent "$http_referer" "$http_user_agent"';
access_log /var/log/nginx/access.log main;
sendfile on;
keepalive_timeout 65;
include /etc/nginx/mime.types;
default_type application/octet-stream;
include /etc/nginx/conf.d/*.conf;
server {
listen 80;
server_name localhost;
location / {
root /usr/share/nginx/html;
index index.html index.htm;
}
}
}5.2 Global Variables
Common variables include $host, $request_method, $remote_addr, $args, $http_user_agent, $server_port, etc.
6. Virtual Host for a Sub‑Domain
# /etc/nginx/conf.d/fe.sherlocked93.club.conf
server {
listen 80;
server_name fe.sherlocked93.club;
location / {
root /usr/share/nginx/html/fe;
index index.html;
}
}7. Reverse Proxy Configuration
# Edit /etc/nginx/nginx.conf, add inside a server block
location / {
proxy_pass http://backend.example.com;
}
nginx -s reloadMultiple upstreams can be defined, e.g., forwarding /edu to 127.0.0.1:8080 and /vod to 127.0.0.1:8081.
8. CORS (Cross‑Origin) Setup
# /etc/nginx/conf.d/be.sherlocked93.club.conf
server {
listen 80;
server_name be.sherlocked93.club;
add_header 'Access-Control-Allow-Origin' $http_origin;
add_header 'Access-Control-Allow-Credentials' 'true';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
add_header 'Access-Control-Allow-Headers' $http_access_control_request_headers;
if ($request_method = 'OPTIONS') {
add_header 'Access-Control-Max-Age' 1728000;
add_header 'Content-Type' 'text/plain; charset=utf-8';
add_header 'Content-Length' 0;
return 204;
}
location / {
root /usr/share/nginx/html/be;
index index.html;
}
}9. Enable Gzip Compression
# /etc/nginx/conf.d/gzip.conf
gzip on;
gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;
gzip_static on;
gzip_proxied any;
gzip_vary on;
gzip_comp_level 6;
gzip_buffers 16 8k;
gzip_http_version 1.1;Gzip reduces response size dramatically; configure gzip_min_length (e.g., 1k) to avoid compressing tiny files.
9.2 Webpack Gzip Plugin
const CompressionWebpackPlugin = require('compression-webpack-plugin');
module.exports = {
configureWebpack: config => {
if (process.env.NODE_ENV === 'production') {
return {
plugins: [new CompressionWebpackPlugin({
test: /\.js$|\.html$|\.css/,
threshold: 10240,
deleteOriginalAssets: false
})]
};
}
}
};10. Load Balancing Configuration
http {
upstream myserver {
server 127.0.0.1:8081;
server 127.0.0.1:8080;
server 127.0.0.1:8082 weight=10;
}
server {
location / {
proxy_pass http://myserver;
proxy_connect_timeout 10;
}
}
}Supported methods: round‑robin (default), weight, ip_hash, and third‑party fair.
11. Static/Dynamic Separation
server {
location /www/ { root /data/; index index.html; }
location /image/ { root /data/; autoindex on; }
}Use expires to set cache lifetimes for static assets.
12. High‑Availability with Keepalived
# Install keepalived
yum install keepalived -y
# /etc/keepalived/keepalived.conf (excerpt)
global_defs {
router_id LVS_DEVEL
}
vrrp_script chk_maintainace {
script "[[ -e /etc/keepalived/down ]] && exit 1 || exit 0"
interval 2
weight -20
}
vrrp_instance VI_1 {
state MASTER
interface eth0
virtual_router_id 51
priority 100
advert_int 1
authentication { auth_type PASS; auth_pass 1111; }
virtual_ipaddress { 172.16.2.8 }
track_script { chk_maintainace }
}A helper script nginx_check.sh restarts Nginx if it crashes; the backup node takes over the virtual IP.
13. Device‑Specific Site Delivery
# /etc/nginx/conf.d/fe.sherlocked93.club.conf
server {
listen 80;
server_name fe.sherlocked93.club;
location / {
root /usr/share/nginx/html/pc;
if ($http_user_agent ~* '(Android|webOS|iPhone|iPod|BlackBerry)') {
root /usr/share/nginx/html/mobile;
}
index index.html;
}
}14. HTTPS Setup
server {
listen 443 ssl http2 default_server;
server_name sherlocked93.club;
ssl_certificate /etc/nginx/https/sherlocked93.crt;
ssl_certificate_key /etc/nginx/https/sherlocked93.key;
ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:HIGH:!aNULL:!MD5:!RC4:!DHE;
ssl_prefer_server_ciphers on;
location / {
root /usr/share/nginx/html;
index index.html index.htm;
}
add_header X-Frame-Options DENY;
add_header X-Content-Type-Options nosniff;
add_header X-Xss-Protection 1;
}15. Miscellaneous Tricks
Static file service with alias and autoindex.
Hotlink protection using valid_referers and if ($invalid_referer) { return 403; }.
Request method filtering: if ($request_method !~ ^(GET|POST|HEAD)$) { return 403; }.
Cache control for assets: location ~* \.(css|js|png|jpg|gif)$ { expires 10d; }.
SPA history mode: try_files $uri $uri/ /index.html;.
HTTP→HTTPS 301 redirect using
if ($scheme != 'https') { return 301 https://$host$request_uri; }.
Wildcard domain routing:
server_name ~^([\w-]+)\.doc\.example\.com$; root /usr/share/nginx/html/doc/$1;.
Best practices: separate config files in /etc/nginx/conf.d/, use snippets for reusable blocks, and keep per‑site logs in /var/log/nginx/.
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.
Liangxu Linux
Liangxu, a self‑taught IT professional now working as a Linux development engineer at a Fortune 500 multinational, shares extensive Linux knowledge—fundamentals, applications, tools, plus Git, databases, Raspberry Pi, etc. (Reply “Linux” to receive essential resources.)
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.
