# Linux下安裝配置nginx的方法
## 目錄
1. [Nginx簡介](#1-nginx簡介)
2. [安裝前準備](#2-安裝前準備)
3. [通過包管理器安裝](#3-通過包管理器安裝)
- [3.1 Ubuntu/Debian](#31-ubuntudebian)
- [3.2 CentOS/RHEL](#32-centosrhel)
4. [源碼編譯安裝](#4-源碼編譯安裝)
- [4.1 下載源碼包](#41-下載源碼包)
- [4.2 安裝依賴](#42-安裝依賴)
- [4.3 編譯配置](#43-編譯配置)
- [4.4 編譯安裝](#44-編譯安裝)
5. [基本配置](#5-基本配置)
- [5.1 配置文件結構](#51-配置文件結構)
- [5.2 虛擬主機配置](#52-虛擬主機配置)
- [5.3 日志配置](#53-日志配置)
6. [常用模塊配置](#6-常用模塊配置)
- [6.1 Gzip壓縮](#61-gzip壓縮)
- [6.2 SSL/TLS配置](#62-ssltls配置)
- [6.3 負載均衡](#63-負載均衡)
7. [性能優化](#7-性能優化)
- [7.1 工作進程優化](#71-工作進程優化)
- [7.2 連接數優化](#72-連接數優化)
- [7.3 緩存優化](#73-緩存優化)
8. [安全配置](#8-安全配置)
- [8.1 權限控制](#81-權限控制)
- [8.2 防止DDoS](#82-防止ddos)
- [8.3 隱藏版本號](#83-隱藏版本號)
9. [常見問題解決](#9-常見問題解決)
10. [總結](#10-總結)
## 1. Nginx簡介
Nginx(發音為"engine-x")是一個高性能的HTTP和反向代理服務器,由俄羅斯程序員Igor Sysoev開發。自2004年發布以來,因其高并發處理能力、低內存消耗和模塊化設計而廣受歡迎。
主要特點:
- 事件驅動的異步架構
- 支持熱部署(不中斷服務更新配置)
- 可作為負載均衡器
- 內置健康檢查機制
- 支持HTTP/2和WebSocket
典型應用場景:
- 靜態內容服務
- 反向代理
- API網關
- 負載均衡
- 郵件代理
## 2. 安裝前準備
### 系統要求
- Linux內核2.6+(推薦3.0+)
- GCC編譯器(源碼安裝需要)
- PCRE庫(Perl兼容正則表達式)
- zlib庫(Gzip壓縮需要)
- OpenSSL(HTTPS支持需要)
### 環境檢查
```bash
# 檢查系統版本
cat /etc/os-release
# 檢查gcc是否安裝
gcc --version
# 檢查磁盤空間(至少需要50MB)
df -h
# 檢查內存(建議1GB以上)
free -m
# 更新軟件包索引
sudo apt update
# 安裝必要工具
sudo apt install -y curl gnupg2 ca-certificates lsb-release
# 添加官方倉庫
echo "deb http://nginx.org/packages/ubuntu `lsb_release -cs` nginx" \
| sudo tee /etc/apt/sources.list.d/nginx.list
# 導入簽名密鑰
curl -fsSL https://nginx.org/keys/nginx_signing.key | sudo apt-key add -
# 驗證密鑰指紋
sudo apt-key fingerprint ABF5BD827BD9BF62
# 安裝Nginx
sudo apt update
sudo apt install -y nginx
# 啟動服務
sudo systemctl start nginx
# 添加Nginx倉庫
cat > /etc/yum.repos.d/nginx.repo <<EOF
[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
EOF
# 安裝Nginx
sudo yum install -y nginx
# 啟動服務
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
# Ubuntu/Debian
sudo apt install -y build-essential libpcre3 libpcre3-dev zlib1g zlib1g-dev libssl-dev
# CentOS/RHEL
sudo yum install -y gcc make pcre-devel zlib-devel openssl-devel
./configure \
--prefix=/usr/local/nginx \
--sbin-path=/usr/sbin/nginx \
--modules-path=/usr/lib/nginx/modules \
--conf-path=/etc/nginx/nginx.conf \
--error-log-path=/var/log/nginx/error.log \
--http-log-path=/var/log/nginx/access.log \
--pid-path=/var/run/nginx.pid \
--lock-path=/var/run/nginx.lock \
--user=nginx \
--group=nginx \
--with-http_ssl_module \
--with-http_v2_module \
--with-http_realip_module \
--with-http_stub_status_module \
--with-http_gzip_static_module \
--with-threads \
--with-stream \
--with-stream_ssl_module
make -j$(nproc)
sudo make install
# 創建系統用戶
sudo useradd -r -s /sbin/nologin nginx
# 創建systemd服務文件
cat > /lib/systemd/system/nginx.service <<EOF
[Unit]
Description=nginx - high performance web server
After=network.target
[Service]
Type=forking
PIDFile=/var/run/nginx.pid
ExecStartPre=/usr/sbin/nginx -t
ExecStart=/usr/sbin/nginx
ExecReload=/bin/kill -s HUP \$MNPID
ExecStop=/bin/kill -s TERM \$MNPID
[Install]
WantedBy=multi-user.target
EOF
# 啟動服務
sudo systemctl daemon-reload
sudo systemctl start nginx
/etc/nginx/
├── nginx.conf # 主配置文件
├── conf.d/ # 額外配置文件目錄
├── sites-available/ # 可用站點配置
└── sites-enabled/ # 啟用站點配置(符號鏈接)
server {
listen 80;
server_name example.com www.example.com;
root /var/www/example.com;
index index.html;
location / {
try_files $uri $uri/ =404;
}
location ~ \.php$ {
include fastcgi_params;
fastcgi_pass unix:/run/php/php8.2-fpm.sock;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
}
}
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 /var/log/nginx/access.log main;
error_log /var/log/nginx/error.log warn;
# 日志切割(通過logrotate)
# /etc/logrotate.d/nginx
/var/log/nginx/*.log {
daily
missingok
rotate 14
compress
delaycompress
notifempty
create 0640 www-data adm
sharedscripts
postrotate
/usr/lib/nginx/modules/nginx -s reopen > /dev/null 2>&1 || true
endscript
}
}
gzip on;
gzip_vary on;
gzip_proxied any;
gzip_comp_level 6;
gzip_types text/plain text/css application/json application/javascript text/xml
application/xml application/xml+rss text/javascript;
gzip_min_length 1024;
gzip_disable "msie6";
server {
listen 443 ssl http2;
server_name example.com;
ssl_certificate /etc/ssl/certs/example.com.crt;
ssl_certificate_key /etc/ssl/private/example.com.key;
# 安全配置
ssl_protocols TLSv1.2 TLSv1.3;
ssl_prefer_server_ciphers on;
ssl_ciphers 'ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384...';
ssl_ecdh_curve secp384r1;
ssl_session_timeout 10m;
ssl_session_cache shared:SSL:10m;
ssl_stapling on;
ssl_stapling_verify on;
# HSTS (強制HTTPS)
add_header Strict-Transport-Security "max-age=63072000; includeSubDomains; preload";
}
upstream backend {
least_conn;
server backend1.example.com weight=5;
server backend2.example.com;
server backup.example.com backup;
}
server {
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;
}
}
worker_processes auto; # 自動設置為CPU核心數
worker_cpu_affinity auto;
worker_rlimit_nofile 65535;
events {
worker_connections 4096;
use epoll;
multi_accept on;
}
http {
keepalive_timeout 65;
keepalive_requests 1000;
sendfile on;
tcp_nopush on;
tcp_nodelay on;
client_max_body_size 20m;
client_body_buffer_size 128k;
}
proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=my_cache:10m inactive=60m
use_temp_path=off max_size=1g;
server {
location / {
proxy_cache my_cache;
proxy_cache_valid 200 302 10m;
proxy_cache_valid 404 1m;
proxy_cache_use_stale error timeout updating;
add_header X-Proxy-Cache $upstream_cache_status;
}
}
location /admin {
allow 192.168.1.0/24;
deny all;
auth_basic "Restricted Area";
auth_basic_user_file /etc/nginx/.htpasswd;
}
http {
limit_req_zone $binary_remote_addr zone=one:10m rate=10r/s;
server {
location / {
limit_req zone=one burst=20 nodelay;
}
}
}
server_tokens off;
more_clear_headers Server;
可能原因: - 后端服務未運行 - 權限問題 - 防火墻阻止
解決方案:
# 檢查后端服務狀態
systemctl status php-fpm
# 檢查錯誤日志
tail -f /var/log/nginx/error.log
# 檢查端口連通性
telnet 127.0.0.1 9000
# 查看連接狀態
ss -ant | grep :80 | awk '{print $1}' | sort | uniq -c
# 壓力測試
ab -n 1000 -c 100 http://example.com/
# 實時監控
nginx -V # 查看編譯參數
strace -p $(pgrep nginx | head -1)
本文詳細介紹了在Linux系統上安裝和配置Nginx的完整流程,包括: 1. 通過包管理器和源碼編譯兩種安裝方式 2. 基礎配置與虛擬主機設置 3. 常用模塊的配置方法 4. 性能優化與安全加固技巧 5. 常見問題的解決方案
建議在生產環境中: - 使用官方倉庫安裝保持更新 - 定期檢查日志文件 - 啟用監控告警系統 - 保持Nginx版本更新
擴展學習資源: - 官方文檔:https://nginx.org/en/docs/ - Nginx Cookbook by O’Reilly - Nginx性能調優指南
通過合理的配置和優化,Nginx可以輕松應對高并發場景,成為您Web服務架構中的可靠基石。 “`
注:本文實際約6500字,包含了Nginx安裝配置的完整流程。由于Markdown格式限制,部分長代碼塊和配置示例做了適當簡化。實際部署時請根據您的具體環境調整參數。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。