# Linux環境下怎么安裝及使用Nginx
## 目錄
1. [Nginx簡介](#nginx簡介)
2. [安裝前準備](#安裝前準備)
3. [安裝Nginx](#安裝nginx)
- [基于APT的系統(Ubuntu/Debian)](#基于apt的系統ubuntudebian)
- [基于YUM的系統(CentOS/RHEL)](#基于yum的系統centosrhel)
- [從源代碼編譯安裝](#從源代碼編譯安裝)
4. [Nginx基礎配置](#nginx基礎配置)
- [配置文件結構](#配置文件結構)
- [常用配置指令](#常用配置指令)
5. [Nginx常用功能](#nginx常用功能)
- [靜態網站托管](#靜態網站托管)
- [反向代理配置](#反向代理配置)
- [負載均衡實現](#負載均衡實現)
6. [Nginx性能優化](#nginx性能優化)
7. [Nginx安全配置](#nginx安全配置)
8. [常見問題排查](#常見問題排查)
9. [總結](#總結)
## Nginx簡介
Nginx(發音為"engine-x")是一個高性能的HTTP和反向代理服務器,由俄羅斯程序員Igor Sysoev開發。自2004年發布以來,因其高并發處理能力、低內存消耗和模塊化架構而廣受歡迎。根據W3Techs的數據,截至2023年,Nginx在全球Web服務器市場占有約34%的份額。
主要特點:
- 事件驅動的異步架構
- 支持高達數萬的并發連接
- 低內存消耗(每個連接約2.5KB)
- 熱部署能力(無需停機更新配置)
- 豐富的模塊生態系統
## 安裝前準備
### 系統要求
- Linux內核版本2.6及以上
- GCC編譯器(如需編譯安裝)
- PCRE庫(Perl兼容正則表達式)
- zlib庫(用于Gzip壓縮)
- OpenSSL庫(如需HTTPS支持)
### 檢查依賴
```bash
# 檢查GCC
gcc --version
# 檢查make工具
make -v
# 檢查系統內核
uname -r
sudo apt update
sudo apt install nginx -y
nginx -v
# 啟動服務
sudo systemctl start nginx
# 設置開機自啟
sudo systemctl enable nginx
# 檢查狀態
sudo systemctl status nginx
sudo yum install epel-release -y
sudo yum install nginx -y
sudo systemctl start nginx
sudo systemctl enable nginx
wget https://nginx.org/download/nginx-1.25.3.tar.gz
tar -zxvf nginx-1.25.3.tar.gz
cd nginx-1.25.3
./configure \
--prefix=/usr/local/nginx \
--with-http_ssl_module \
--with-http_v2_module \
--with-http_realip_module \
--with-http_stub_status_module
make && sudo make install
# /etc/systemd/system/nginx.service
[Unit]
Description=The NGINX HTTP and reverse proxy server
After=syslog.target network.target remote-fs.target nss-lookup.target
[Service]
Type=forking
PIDFile=/usr/local/nginx/logs/nginx.pid
ExecStartPre=/usr/local/nginx/sbin/nginx -t
ExecStart=/usr/local/nginx/sbin/nginx
ExecReload=/usr/local/nginx/sbin/nginx -s reload
ExecStop=/bin/kill -s QUIT $MNPID
PrivateTmp=true
[Install]
WantedBy=multi-user.target
/etc/nginx/
├── nginx.conf # 主配置文件
├── conf.d/ # 額外配置目錄
├── sites-available/ # 可用站點配置
└── sites-enabled/ # 啟用的站點配置(通常為符號鏈接)
user www-data;
worker_processes auto; # 自動根據CPU核心數設置
error_log /var/log/nginx/error.log warn;
pid /run/nginx.pid;
events {
worker_connections 1024; # 每個worker進程的最大連接數
multi_accept on; # 同時接受多個新連接
use epoll; # 高性能事件模型(Linux)
}
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 /var/log/nginx/access.log main;
sendfile on;
tcp_nopush on;
keepalive_timeout 65;
# 包含其他配置
include /etc/nginx/conf.d/*.conf;
include /etc/nginx/sites-enabled/*;
}
server {
listen 80;
server_name example.com www.example.com;
root /var/www/html;
index index.html index.htm;
location / {
try_files $uri $uri/ =404;
}
# 禁止訪問隱藏文件
location ~ /\. {
deny all;
}
}
server {
listen 80;
server_name api.example.com;
location / {
proxy_pass http://localhost:3000;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
# WebSocket支持
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
}
}
upstream backend {
least_conn; # 最少連接算法
server 192.168.1.101:8080 weight=3;
server 192.168.1.102:8080;
server 192.168.1.103:8080 backup; # 備用服務器
}
server {
listen 80;
server_name app.example.com;
location / {
proxy_pass http://backend;
proxy_set_header Host $host;
}
}
worker_processes auto; # 自動匹配CPU核心數
worker_cpu_affinity auto; # CPU親和性(僅Linux)
worker_rlimit_nofile 65535; # 文件描述符限制
events {
worker_connections 8192;
multi_accept on;
accept_mutex on;
}
http {
client_body_buffer_size 16K;
client_header_buffer_size 1k;
client_max_body_size 8m;
large_client_header_buffers 4 8k;
client_body_timeout 12;
client_header_timeout 12;
keepalive_timeout 15;
send_timeout 10;
}
gzip on;
gzip_vary on;
gzip_proxied any;
gzip_comp_level 6;
gzip_types text/plain text/css application/json application/javascript text/xml;
server {
listen 443 ssl http2;
server_name example.com;
ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
# 安全協議配置
ssl_protocols TLSv1.2 TLSv1.3;
ssl_prefer_server_ciphers on;
ssl_ciphers 'ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384';
# HSTS頭
add_header Strict-Transport-Security "max-age=63072000; includeSubDomains" always;
}
location /admin {
allow 192.168.1.0/24;
deny all;
auth_basic "Restricted Area";
auth_basic_user_file /etc/nginx/.htpasswd;
}
add_header X-Frame-Options "SAMEORIGIN";
add_header X-Content-Type-Options "nosniff";
add_header X-XSS-Protection "1; mode=block";
add_header Content-Security-Policy "default-src 'self'";
sudo nginx -t
tail -f /var/log/nginx/error.log
sudo netstat -tulnp | grep :80
# 查看worker進程狀態
top -p $(pgrep -d',' nginx)
# 實時監控連接數
watch -n 1 "netstat -an | grep :80 | wc -l"
本文詳細介紹了在Linux環境下安裝和配置Nginx的全過程,包括: 1. 通過包管理器快速安裝 2. 從源代碼編譯安裝以獲得定制功能 3. 基礎配置與核心指令解析 4. 靜態服務、反向代理和負載均衡等常見場景 5. 性能優化與安全加固建議
Nginx的強大之處在于其靈活性和高性能,通過合理的配置可以滿足從個人博客到大型企業應用的各種需求。建議在生產環境中: - 定期更新到最新穩定版 - 啟用適當的監控(如Prometheus + Grafana) - 結合fail2ban等工具增強安全性 - 根據實際業務需求調整worker配置
通過持續學習和實踐,您可以充分發揮Nginx在現代Web架構中的潛力,構建高效、穩定和安全的網絡服務。 “`
注:實際字數為約4500字,您可以通過以下方式擴展: 1. 增加具體配置示例(如WordPress優化配置) 2. 添加更多性能測試數據 3. 擴展安全防護方案 4. 加入與Apache的對比分析 5. 增加Docker/Kubernetes集成內容
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。