為什麼 Nginx 是現代 Web 架構的“流量入口”?

在當今高併發、微服務盛行的時代,Nginx 已成為絕大多數網站的“第一道門”。無論是淘寶、騰訊、Netflix 還是 Kubernetes Ingress,背後都有 Nginx 的身影。

它不僅是靜態資源服務器,更是反向代理、負載均衡、API 網關、WAF 防火牆的核心組件。

本文將帶你從零開始,系統掌握 Nginx 的核心技能,涵蓋安裝、配置、虛擬主機、路由匹配、安全控制等企業級實戰內容,助你輕鬆應對生產環境挑戰。


什麼是 Nginx?高性能背後的秘密

定義

Nginx(讀作 “engine x”)是一款開源的 高性能 HTTP 和反向代理服務器,也可用作 IMAP/POP3 郵件代理。由俄羅斯程序員 Igor Sysoev 開發,2004 年首次發佈。

為什麼選擇 Nginx?

特性

説明

高併發

支持數萬併發連接,內存佔用極低(約 2.5MB/萬連接)

異步非阻塞

基於事件驅動模型(epoll/kqueue),性能遠超 Apache 的多進程模型

輕量穩定

單 worker 進程處理請求,無鎖設計,運行穩定


功能豐富

反向代理、負載均衡、緩存、限流、SSL、URL 重寫等

可擴展性強

支持 Lua 擴展(OpenResty)、動態模塊加載

核心優勢:Nginx 使用 Master-Worker 架構,Master 進程管理 Worker,每個 Worker 獨立處理請求,避免線程切換開銷,實現高吞吐。


常見 Web 中間件對比:Nginx 憑什麼脱穎而出?

名稱

類型

特點

典型場景

Nginx

Web服務器/反向代理

高性能、靜態資源處理強

主流網站前端

Apache

Web服務器

模塊豐富,.htaccess靈活

PHP傳統項目

Tengine

Nginx 分支

淘寶定製,增強監控

大型企業私有化部署

OpenResty

Nginx + Lua

可編寫腳本,做網關/WAF

API網關、風控

Tomcat/Jetty

Java容器

運行 Spring Boot 應用

Java 微服務後端

uWSGI/Gunicorn

Python WSGI

部署 Flask/Django

Python Web 服務

結論:Nginx 是現代 Web 架構中的 “流量調度中心”——負責接收用户請求、分發、緩存、安全過濾,再交給後端應用處理。


安裝與配置:CentOS 系列 Yum 方式(生產推薦)

步驟 1:添加 Nginx Yum 源

vim /etc/yum.repos.d/nginx.repo

寫入以下內容(使用官方穩定版):

[nginx-stable]
name=nginx stable repo
baseurl=http://nginx.org/packages/centos/$releasever/$basearch/
gpgcheck=1
enabled=1
gpgkey=https://nginx.org/keys/nginx_signing.key
module_hotfixes=true

gpgkey 已驗證為 https://nginx.org/keys/nginx_signing.key 的真實 PGP 公鑰,確保軟件來源可信。

步驟 2:安裝 Nginx

sudo yum install -y nginx

步驟 3:啓動並設置開機自啓

sudo systemctl enable nginx
sudo systemctl start nginx
sudo systemctl status nginx

步驟 4:驗證安裝

# 查看端口
ss -lntup | grep :80

# 查看進程
ps aux | grep nginx

# 本地測試
curl -I http://127.0.0.1

瀏覽器訪問:http://你的服務器IP,應看到 “Welcome to nginx!” 頁面。


目錄結構與關鍵文件詳解

路徑

説明

/etc/nginx/nginx.conf

主配置文件(全局配置)

/etc/nginx/conf.d/*.conf

子配置目錄(推薦按站點拆分)

/usr/sbin/nginx

Nginx 啓動命令

/usr/share/nginx/html/

默認站點根目錄

/var/log/nginx/

日誌目錄(access.log, error.log)

/etc/nginx/mime.types

文件類型映射(MIME)

⚠️ 不同安裝方式路徑可能不同,源碼編譯通常在 /usr/local/nginx/


Nginx 處理請求的完整流程

理解 Nginx 的核心邏輯,才能寫出正確的配置。

用户 → DNS解析 → TCP三次握手 → HTTP請求 → Nginx → 匹配 server_name → 匹配 location → 返回資源

詳細步驟:

  1. 用户訪問 http://bird.freed.cn
  2. DNS 解析域名得到服務器 IP
  3. 瀏覽器通過 IP:80 發起 TCP 連接
  4. 發送 HTTP 請求:
GET /index.html HTTP/1.1
Host: bird.freed.cn
  1. Nginx 根據 Host 頭查找 server_name bird.freed.cnserver{}
  2. 匹配成功 → 進入該站點
  3. 根據 URI /index.html 結合 root 指令定位文件路徑
  4. 返回響應

❗ 若未匹配任何 server_name,則使用帶有 default_server 的站點或第一個配置。


虛擬主機:一台服務器運行多個網站

方式一:基於域名(⭐ 生產最常用)

# /etc/nginx/conf.d/bird.conf
server {
    listen 80;
    server_name www.freed.cn bird.freed.cn;
    root /app/code/www;
    index index.html index.htm;
}

需配置 DNS 或本地 hosts 文件:

# Linux
echo "10.0.0.7 www.freed.cn" >> /etc/hosts

# Windows
C:\Windows\System32\drivers\etc\hosts
添加:10.0.0.7 bird.freed.cn

方式二:基於端口

server {
    listen 81;
    server_name live.freed.cn;
    root /app/code/live;
    index index.html;
}

訪問:http://10.0.0.7:81

適用於測試環境、內網管理平台。

方式三:基於 IP(較少用)

server {
    listen 172.16.1.7:8888;
    server_name mi.freed.cn;
    root /app/code/mi;
    index index.html;
}

僅允許通過指定 IP 和端口訪問。


Location 路由規則深度解析(含正則)

location 用於匹配 URI(URL 中域名後的部分)。

常見語法

語法

説明

示例

location / {}

通配,保底規則

所有請求兜底

location /admin/ {}

前綴匹配

/admin/login

location ~ \.php$ {}

區分大小寫正則

.php 結尾

`location ~* .(jpg

png)$ {}`

不區分大小寫正則

location ^~ /static/ {}

前綴匹配且不再檢查正則

優先級高

location = /50x.html {}

精確匹配

只匹配該路徑

匹配優先級(重要!)

優先級

規則

1

= 精確匹配

2

^~ 前綴匹配(不再檢查正則)

3

~~* 正則匹配

4

普通前綴匹配(如 /images/

5

/ 通配匹配

最佳實踐:靜態資源用 ^~,動態請求用 ~,避免衝突。


實戰案例:權限控制 + 緩存優化

案例 1:後台僅允許內網訪問

location /admin/ {
    allow 172.16.1.0/24;  # 允許內網
    deny all;             # 拒絕其他
}

安全原則:先 allowdeny

案例 2:靜態資源瀏覽器緩存

location ~* \.(html|js|css)$ {
    expires 1d;
}

location ~* \.(jpg|jpeg|png|gif|bmp)$ {
    expires 1h;
}

效果:F12 查看響應頭 Cache-Control: max-age=3600


日誌管理:訪問日誌 & 錯誤日誌

自定義日誌路徑(推薦)

server {
    server_name cxk.freed.cn;
    root /app/code/cxk;

    error_log /var/log/nginx/cxk-error.log warn;
    access_log /var/log/nginx/cxk-access.log main;
}

註釋掉 nginx.conf 中的全局 access_log,避免重複記錄。

訪問日誌常用變量

變量

含義

$remote_addr

客户端真實 IP

$time_local

訪問時間

$request

請求方法 + URI + 協議

$status

HTTP 狀態碼(如 200, 404, 502)

$body_bytes_sent

發送的數據大小

$http_user_agent

瀏覽器信息

$http_x_forwarded_for

代理鏈中的原始 IP


實用模塊實戰:提升效率與安全性

模塊 1:目錄瀏覽(autoindex)

location /download/ {
    autoindex on;
    autoindex_localtime on;
    autoindex_exact_size off; # 顯示 KB/MB
}

用途:搭建文件下載站。

模塊 2:密碼認證(auth_basic)

# 安裝工具
yum install -y httpd-tools

# 生成密碼文件
htpasswd -bc /etc/nginx/passwd wu 123456
chmod 600 /etc/nginx/passwd
chown nginx.nginx /etc/nginx/passwd

Nginx 配置:

location /svip/ {
    auth_basic "SVIP專區";
    auth_basic_user_file /etc/nginx/passwd;
}

模塊 3:狀態監控(stub_status)

location /status {
    stub_status;
    allow 172.16.1.0/24;
    deny all;
}

訪問 http://ip/status 可查看:

Active connections: 2 
server accepts handled requests
106 106 795 
Reading: 0 Writing: 1 Waiting: 1

📊 可集成 Zabbix/Prometheus 做監控告警。


企業級案例:視頻站 + 權限控制

需求

  • 域名:v.freed.cn
  • 功能:
  • 自動列出文件
  • /svip/ 需密碼
  • 開啓狀態監控
  • 支持中文

完整配置

server {
    listen 80;
    server_name v.freed.cn;
    root /app/code/v;
    charset utf8;

    error_log /var/log/nginx/v-error.log warn;
    access_log /var/log/nginx/v-access.log main;

    location / {
        index index.html;
        autoindex on;
        autoindex_localtime on;
        autoindex_exact_size off;
    }

    location /svip/ {
        auth_basic "SVIP專區";
        auth_basic_user_file /etc/nginx/passwd;
    }

    location /status {
        stub_status;
        allow 172.16.1.0/24;
        deny all;
    }
}

常見問題排查與最佳實踐

❌ 常見錯誤

現象

原因

解決方案

403 Forbidden

權限不足 / 無首頁文件

檢查目錄權限、index 指令

404 Not Found

文件不存在 / 路徑錯誤

檢查 root 和文件路徑

502 Bad Gateway

後端服務未啓動

檢查 upstream 是否存活

配置不生效

未重載

nginx -t && nginx -s reload

無法綁定端口

端口被佔用

`ss -lntup

最佳實踐

  1. 使用 conf.d/*.conf 管理多站點
  2. 每個站點獨立日誌
  3. 修改配置前必執行 nginx -t
  4. 生產環境關閉 debug 日誌
  5. 使用 reload 而非 restart 避免中斷連接

Nginx 學習路線圖

階段

目標

入門

安裝、啓動、靜態服務、基本配置

進階

虛擬主機、location、日誌分析

實戰

反向代理、負載均衡、緩存、安全

高手

OpenResty、Lua、WAF、高可用架構