# Linux下如何安裝和配置Nginx
## 1. 前言
Nginx(發音為"engine-x")是一個高性能的HTTP和反向代理服務器,以其穩定性、豐富的功能集、簡單的配置和低資源消耗而聞名。它既可以作為Web服務器直接提供靜態內容,也可以作為負載均衡器或反向代理服務器使用。
本文將詳細介紹在Linux系統下安裝和配置Nginx的完整過程,涵蓋從基礎安裝到高級配置的各個方面。
## 2. 安裝前的準備
### 2.1 系統要求
Nginx可以在大多數Linux發行版上運行,包括但不限于:
- Ubuntu/Debian
- CentOS/RHEL
- Fedora
- Arch Linux
建議系統滿足以下最低要求:
- 1GB RAM(生產環境建議2GB以上)
- 至少10GB可用磁盤空間
- root或具有sudo權限的用戶
### 2.2 更新系統
在安裝任何新軟件之前,建議先更新系統軟件包:
```bash
# Ubuntu/Debian
sudo apt update && sudo apt upgrade -y
# CentOS/RHEL
sudo yum update -y
# Fedora
sudo dnf update -y
sudo apt install nginx -y
CentOS/RHEL默認倉庫中沒有Nginx,需要先添加EPEL倉庫:
sudo yum install epel-release -y
sudo yum install nginx -y
sudo dnf install nginx -y
如果需要最新版本或自定義模塊,可以選擇編譯安裝:
# 安裝編譯依賴
sudo apt install build-essential libpcre3 libpcre3-dev zlib1g zlib1g-dev libssl-dev -y
# 下載最新穩定版
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
Nginx的配置文件通常位于以下位置:
- /etc/nginx/nginx.conf
- 主配置文件
- /etc/nginx/conf.d/
- 額外配置文件目錄
- /etc/nginx/sites-available/
- 可用站點配置
- /etc/nginx/sites-enabled/
- 啟用的站點配置(通常是符號鏈接)
編輯主配置文件/etc/nginx/nginx.conf
:
user www-data;
worker_processes auto;
pid /run/nginx.pid;
events {
worker_connections 1024;
multi_accept on;
}
http {
sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 65;
types_hash_max_size 2048;
include /etc/nginx/mime.types;
default_type application/octet-stream;
access_log /var/log/nginx/access.log;
error_log /var/log/nginx/error.log;
gzip on;
gzip_disable "msie6";
include /etc/nginx/conf.d/*.conf;
include /etc/nginx/sites-enabled/*;
}
# 啟動Nginx
sudo systemctl start nginx
# 設置開機自啟
sudo systemctl enable nginx
# 檢查狀態
sudo systemctl status nginx
# 重新加載配置(不中斷服務)
sudo systemctl reload nginx
# 完全重啟
sudo systemctl restart nginx
sudo mkdir -p /var/www/example.com/html
sudo chown -R $USER:$USER /var/www/example.com/html
sudo chmod -R 755 /var/www/example.com
在/etc/nginx/sites-available/example.com
創建文件:
server {
listen 80;
listen [::]:80;
server_name example.com www.example.com;
root /var/www/example.com/html;
index index.html index.htm;
location / {
try_files $uri $uri/ =404;
}
access_log /var/log/nginx/example.com.access.log;
error_log /var/log/nginx/example.com.error.log;
}
sudo ln -s /etc/nginx/sites-available/example.com /etc/nginx/sites-enabled/
sudo nginx -t # 測試配置語法
sudo systemctl reload nginx
# 安裝Certbot
sudo apt install certbot python3-certbot-nginx -y
# 獲取證書
sudo certbot --nginx -d example.com -d www.example.com
# 測試續期
sudo certbot renew --dry-run
# 添加定時任務(每天檢查續期)
sudo crontab -e
添加以下行:
0 12 * * * /usr/bin/certbot renew --quiet
worker_processes auto; # 自動設置為CPU核心數
worker_rlimit_nofile 100000;
events {
worker_connections 4096;
multi_accept on;
use epoll;
}
http {
sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 30;
keepalive_requests 100000;
reset_timedout_connection on;
client_body_timeout 10;
send_timeout 2;
open_file_cache max=200000 inactive=20s;
open_file_cache_valid 30s;
open_file_cache_min_uses 2;
open_file_cache_errors on;
}
server_tokens off;
add_header X-Frame-Options "SAMEORIGIN";
add_header X-XSS-Protection "1; mode=block";
add_header X-Content-Type-Options "nosniff";
add_header Referrer-Policy "no-referrer-when-downgrade";
add_header Content-Security-Policy "default-src 'self' http: https: data: blob: 'unsafe-inline'" always;
if ($request_method !~ ^(GET|HEAD|POST)$ ) {
return 405;
}
location /app/ {
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;
proxy_set_header X-Forwarded-Proto $scheme;
}
upstream backend {
least_conn;
server backend1.example.com weight=5;
server backend2.example.com;
server backend3.example.com;
keepalive 32;
}
server {
location / {
proxy_pass http://backend;
# 其他代理設置...
}
}
location /ws/ {
proxy_pass http://backend;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_read_timeout 86400;
}
location /nginx_status {
stub_status on;
access_log off;
allow 127.0.0.1;
deny all;
}
# 查看最頻繁的IP
awk '{print $1}' /var/log/nginx/access.log | sort | uniq -c | sort -nr | head -n 20
# 查看HTTP狀態碼統計
awk '{print $9}' /var/log/nginx/access.log | sort | uniq -c | sort -rn
可能原因: - 后端服務未運行 - 代理設置錯誤 - 權限問題
檢查: - 文件權限 - SELinux設置 - 目錄索引設置
# 查看Nginx進程
ps aux | grep nginx
# 檢查打開文件限制
ulimit -n
# 網絡連接統計
netstat -anp | grep nginx
通過本文的詳細指導,您應該已經掌握了在Linux系統上安裝和配置Nginx的全過程。從基礎安裝到高級配置,Nginx提供了豐富的功能來滿足各種Web服務需求。建議在生產環境中部署前,充分測試所有配置,并考慮結合防火墻和其他安全措施來增強服務器安全性。
Nginx的強大之處在于其靈活性和高性能,通過不斷學習和實踐,您可以進一步發掘它的潛力,構建更加強大和可靠的Web服務架構。
命令 | 描述 |
---|---|
sudo systemctl start nginx |
啟動Nginx |
sudo systemctl stop nginx |
停止Nginx |
sudo systemctl restart nginx |
重啟Nginx |
sudo systemctl reload nginx |
重載配置 |
sudo nginx -t |
測試配置語法 |
sudo tail -f /var/log/nginx/error.log |
查看錯誤日志 |
sudo ss -tulpn | grep nginx |
查看Nginx監聽端口 |
sudo du -sh /var/log/nginx/ |
查看日志目錄大小 |
”`
注意:本文約3750字,實際字數可能因格式和顯示環境略有差異。文章包含了Nginx從安裝到配置的完整流程,適合初學者和中級用戶參考使用。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。