Master Nginx: Complete Installation, Configuration, and Advanced Tips

This comprehensive guide walks you through installing Nginx from source, configuring global settings, mastering common directives, enabling gzip compression, setting up reverse and forward proxies, load balancing, SSL, systemd service management, and troubleshooting, providing ready-to-use code snippets and practical examples for server administrators.

QQ Music Frontend Team
QQ Music Frontend Team
QQ Music Frontend Team
Master Nginx: Complete Installation, Configuration, and Advanced Tips

When reviewing Nginx, I compiled the most commonly used Nginx operations for quick reference; this article covers installation, global configuration, and frequently used settings in detail.

Install Nginx

Download the Nginx tarball to the root directory. Official download URL: nginx.org/download/nginx-x.xx.xx.tar.gz

yum update # update system packages
cd /
wget nginx.org/download/nginx-1.17.2.tar.gz

Extract the tar.gz file and enter the extracted directory.

tar -xzvf nginx-1.17.2.tar.gz
cd nginx-1.17.2

Run the configuration check. ./configure If the check reports missing dependencies, install the required libraries first.

yum -y install pcre*   # enable rewrite support
yum -y install gcc-c++
yum -y install zlib*
yum -y install openssl openssl-devel

Run ./configure again; if no errors appear, proceed to compile and install.

# Check module support
./configure --prefix=/usr/local/nginx \
    --with-http_ssl_module --with-http_v2_module --with-http_realip_module \
    --with-http_addition_module --with-http_sub_module --with-http_dav_module \
    --with-http_flv_module --with-http_mp4_module --with-http_gunzip_module \
    --with-http_gzip_static_module --with-http_auth_request_module \
    --with-http_random_index_module --with-http_secure_link_module \
    --with-http_degradation_module --with-http_slice_module \
    --with-http_stub_status_module --with-mail --with-mail_ssl_module \
    --with-stream --with-stream_ssl_module --with-stream_realip_module \
    --with-stream_ssl_preread_module --with-threads --user=www --group=www

Pay special attention to the modules you need; missing modules later will require rebuilding.

View the default compiled modules.

Command ls nginx-1.17.2 shows an auto directory. Inside, the options file records all compile‑time options. You can view them with: cat nginx-1.17.2/auto/options | grep YES Compile and install. make && make install Make sure the required modules (e.g., SSL, gzip) are present before compiling.

Check the installation directory.

whereis nginx
# nginx: /usr/local/nginx

Start the Nginx service.

cd /usr/local/nginx/sbin/
./nginx

If startup fails with

nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Address already in use)

, find the process using port 80:

netstat -ntpl
kill <span>PID</span>

After killing the conflicting process, start Nginx again: ./nginx Visiting the server IP in a browser should display "Welcome to Nginx!" indicating a successful installation.

Nginx Configuration

Basic Structure

main        # global configuration
├── events  # network connection settings
├── http    # proxy, cache, log, and most modules
│   ├── upstream # backend server definitions for load balancing
│   ├── server   # virtual host parameters; multiple server blocks allowed
│   │   ├── location # URI matching inside a server block
│   │   └── ...
│   └── ...
└── ...

Main Directives Meaning

main: global configuration.

events: affects server and client network connections.

http: contains most functionality, including proxy, cache, logs, and third‑party modules.

server: virtual host parameters; an http block can contain multiple servers.

location: matches request URIs and defines handling.

upstream: defines backend server addresses for load balancing.

nginx.conf Syntax Rules

Configuration consists of directives and directive blocks.

Each directive ends with a semicolon; parameters are separated by spaces.

Directive blocks are enclosed in curly braces {}.

The include statement allows combining multiple files.

Comments start with # for readability.

Variables are referenced with the $ symbol.

Some directive parameters support regular expressions (e.g., location).

Built‑in Variables

Commonly used built‑in variables can be used freely in configurations:

TCP

UDP

$host

Host header or server name if missing.

$request_method

Client request method (GET, POST, …).

$remote_addr

Client IP address.

$args

Query string parameters.

$content_length

Content‑Length header value.

$http_user_agent

User‑Agent string.

$http_cookie

Cookie header.

$remote_port

Client port.

$server_protocol

Protocol used (e.g., HTTP/1.1).

$server_addr

Server IP address.

$server_name

Server name.

$server_port

Server listening port.

Common Commands

Useful Nginx control commands:

nginx -s reload   # reload configuration (hot restart)
nginx -s reopen   # reopen log files
nginx -s stop     # fast shutdown
nginx -s quit     # graceful shutdown
nginx -T          # display final configuration
nginx -t -c <path>  # test configuration file

Systemd service commands:

systemctl start nginx
systemctl stop nginx
systemctl restart nginx
systemctl reload nginx   # reload after config change
systemctl enable nginx   # enable at boot
systemctl disable nginx  # disable at boot
systemctl status nginx

Enable Nginx Autostart

With a yum installation, nginx.service is created automatically. Enable it with:

systemctl enable nginx
systemctl disable nginx

Or create a custom service file: vi /lib/systemd/system/nginx.service Example content:

[Unit]
Description=nginx
After=network.target

[Service]
Type=forking
ExecStart=/usr/local/nginx/sbin/nginx
ExecReload=/usr/local/nginx/sbin/nginx -s reload
ExecStop=/usr/local/nginx/sbin/nginx -s quit
PrivateTmp=true

[Install]
WantedBy=multi-user.target

Reload systemd and manage the service:

systemctl daemon-reload
systemctl start nginx.service
systemctl enable nginx.service
systemctl status nginx.service

Make Nginx Commands Global

Add the binary directory to PATH:

vi /etc/profile
export PATH=$PATH:/usr/local/nginx/sbin
source /etc/profile

Common Nginx Features

Reverse Proxy

Typical reverse‑proxy configuration for cross‑origin requests and caching:

server {
    listen 8080;
    # Proxy all /test to GitHub
    location /test {
        proxy_pass https://github.com;
    }
    # Proxy /api to a local service on port 8888
    location /api {
        proxy_pass http://127.0.0.1:8888;
    }
}

Access Control

server {
    location ~ ^/index.html {
        deny 192.168.1.1;
        deny 192.168.1.2;
        allow all;
    }
}

Load Balancing

Four built‑in strategies plus two third‑party ones.

Round‑robin (default)

http {
    upstream test.com {
        server 192.168.1.12:8887;
        server 192.168.1.13:8888;
    }
    server {
        location /api { proxy_pass http://test.com; }
    }
}

Weighted servers

http {
    upstream test.com {
        server 192.168.1.12:8887 weight=9;
        server 192.168.1.13:8888 weight=1;
    }
    server { location /api { proxy_pass http://test.com; } }
}

IP hash (client‑IP binding)

http {
    upstream test.com { ip_hash; server 192.168.1.12:8887; server 192.168.1.13:8888; }
    server { location /api { proxy_pass http://test.com; } }
}

Least connections

http {
    upstream test.com { least_conn; server 192.168.1.12:8887; server 192.168.1.13:8888; }
    server { location /api { proxy_pass http://test.com; } }
}

Fair (NGINX Plus only)

http {
    upstream test.com { fair; server 192.168.1.12:8887; server 192.168.1.13:8888; }
    server { location /api { proxy_pass http://test.com; } }
}

Hash by request URI

http {
    upstream test.com {
        hash $request_uri;
        hash_method crc32;
        server 192.168.1.12:8887;
        server 192.168.1.13:8888;
    }
    server { location /api { proxy_pass http://test.com; } }
}

gzip Compression

Enable gzip to reduce response size and improve speed:

gzip on;
# gzip_types ...
# gzip_static on;
# gzip_proxied expired no-cache no-store private auth;
# gzip_buffers 16 8k;
gzip_min_length 1k;
gzip_comp_level 4;
gzip_http_version 1.0;
gzip_vary off;
gzip_disable "MSIE [1-6]\.";

Explanation of each directive is provided in the original article.

Static HTTP Server

server {
    listen 80;
    server_name localhost;
    location / {
        root /usr/local/app;
        index index.html;
    }
}

Dynamic‑Static Separation

# Serve static files
location ~ \.(gif|jpg|jpeg|png|bmp|swf|css|js)$ {
    root /usr/local/resource;
    expires 10h;
}
# Proxy dynamic requests to Tomcat
location ~ \.(jsp|do)$ { proxy_pass 127.0.0.1:8888; }

Request Rate Limiting

Limit connections per IP:

http {
    limit_conn_zone $binary_remote_addr zone=perip:10m;
    server {
        location / { limit_conn addr 5; }
    }
}

Limit request rate:

limit_req_zone $binary_remote_addr zone=creq:10m rate=10r/s;
server { location / { limit_req zone=creq burst=5; } }

Forward Proxy

Forward proxy forwards client requests to the target host:

resolver 8.8.8.8;
server {
    resolver_timeout 5s;
    location / {
        proxy_pass http://$host$request_uri;
    }
}

Image Hotlink Protection

server {
    listen 80;
    server_name *.test;
    location ~* \.(gif|jpg|jpeg|png|bmp|swf)$ {
        valid_referers none blocked server_names ~\.google\. ~\.baidu\. *.qq.com;
        if ($invalid_referer) { return 403; }
    }
}

Device‑Specific Site

server {
    listen 80;
    server_name test.com;
    location / {
        root /usr/local/app/pc;
        if ($http_user_agent ~* '(Android|webOS|iPhone|iPod|BlackBerry)') {
            root /usr/local/app/mobile;
        }
        index index.html;
    }
}

Sub‑domain Configuration

server {
    listen 80;
    server_name admin.test.com;
    location / {
        root /usr/local/app/admin;
        index index.html;
    }
}

HTTPS Setup (Certbot)

Install Certbot and obtain a free certificate (valid for 3 months):

wget https://dl.eff.org/certbot-auto
chmod a+x certbot-auto
sudo ./certbot-auto certonly --standalone --email [email protected] -d test.com -d www.test.com

Configure Nginx:

server {
    listen 443 ssl http2;
    ssl_certificate /etc/letsencrypt/live/test.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/test.com/privkey.pem;
    server_name test.com www.test.com;
}

Redirect HTTP to HTTPS

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

Single‑Page Application History Routing

server {
    listen 80;
    server_name fe.sherlocked93.club;
    location / {
        root /usr/local/app/dist;
        index index.html index.htm;
        try_files $uri $uri/ /index.html @rewrites;
        expires -1;
        add_header Cache-Control no-cache;
    }
    location @rewrites { rewrite ^(.+)$ /index.html break; }
}

High‑Availability (Keepalived)

Install keepalived and configure a VRRP instance for failover:

yum install keepalived -y
# /etc/keepalived/keepalived.conf (excerpt)
global_defs {
    notification_email { [email protected] }
    notification_email_from [email protected]
    smtp_server 127.0.0.1
    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; }
}

Sample nginx_check.sh script to restart Nginx and trigger failover if it stays down:

#!/bin/bash
A=$(ps -C nginx --no-header | wc -l)
if [ $A -eq 0 ]; then
    /usr/sbin/nginx
    sleep 2
    if [ $(ps -C nginx --no-header | wc -l) -eq 0 ]; then
        killall keepalived
    fi
fi

Proxy Cache

proxy_cache_path /usr/local/cache levels=1:2 keys_zone=my_cache:10m;
server {
    listen 80;
    server_name test.com;
    location / {
        proxy_cache my_cache;
        proxy_pass http://127.0.0.1:8888;
        proxy_set_header Host $host;
    }
}

Access and Error Logs

http {
    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;
    # error_log logs/error.log error;
}

Static Resource Server

server {
    listen 80;
    server_name static.bin;
    charset utf-8;
    location /download {
        alias /usr/share/nginx/static;
        autoindex on;
        autoindex_exact_size off;
        autoindex_localtime off;
    }
}

Block Specific User‑Agents

# Block Baidu, 360, Sohu
if ($http_user_agent ~* 'baidu|360|sohu') { return 404; }
# Block Scrapy, Curl, HttpClient
if ($http_user_agent ~* (Scrapy|Curl|HttpClient)) { return 403; }

Request Filtering

# Allow only GET, POST, HEAD
if ($request_method !~ ^(GET|POST|HEAD)$) { return 403; }
# Custom error page for 502/503
error_page 502 503 /50x.html;
location = /50x.html { root /usr/share/nginx/html; }

ab (ApacheBench) Stress Test

ab -n 1000 -c 5000 http://127.0.0.1/   # 1000 total requests, 5000 concurrency
# Install httpd-tools first:
# yum install httpd-tools

Wildcard Domain Routing

# Map subdomains to directories
server {
    listen 80;
    server_name ~^([\w-]+)\.doc\.test\.club$;
    root /usr/local/html/doc/$1;
}
# Proxy subdomains to backend with path prefix
server {
    listen 80;
    server_name ~^([\w-]+)\.serv\.test\.club$;
    location / {
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $http_host;
        proxy_set_header X-NginX-Proxy true;
        proxy_pass http://127.0.0.1:8080/$1$request_uri;
    }
}

Variable Usage Example

set $name "chroot";
server {
    listen 80;
    server_name test.com;
    location / {
        set $temp hello;
        return "$temp world";
    }
}

When concatenating variables with following characters, use braces to avoid ambiguity:

set $temp "hello ";
return "${temp}world";

To output a literal $, define a variable via geo:

geo $dollar { default "$"; }
server {
    listen 80;
    server_name test.com;
    location / {
        set $temp "hello ";
        return "${temp}world: $dollar";
    }
}

Additional Nginx Modules

Core modules include ngx_core, ngx_errlog, ngx_conf, ngx_events, etc. Standard HTTP modules cover core functionality, logging, upstream, static serving, access control, gzip, SSL, and more. Optional HTTP modules add features such as addition, degradation, Perl, FLV/MP4 streaming, image processing, secure links, and sub‑stitution. Mail modules enable POP3/IMAP/SMTP services. Third‑party modules like echo‑nginx, memc‑nginx, rds‑json‑nginx, and lua‑nginx extend Nginx capabilities.

Thank you for reading~

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 proxyinstallationgzipsystemd
QQ Music Frontend Team
Written by

QQ Music Frontend Team

QQ Music Web Frontend Team

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.