1. Nginx部署前的系统准备
在开始部署Nginx之前,我们需要对服务器进行一系列的基础配置。这些准备工作看似简单,但往往决定了后续部署的成败。我见过太多新手因为跳过这些步骤而导致各种奇怪的问题。
1.1 服务器选择与系统配置
对于生产环境,我强烈推荐使用Ubuntu 22.04 LTS或CentOS Stream 9。这两个系统都有长期支持,社区资源丰富。特别是Ubuntu,对新手更加友好,遇到问题更容易找到解决方案。
bash复制# 查看系统版本
cat /etc/os-release
1.2 系统基础环境配置
这些配置是必须的,否则后续安装Nginx时可能会遇到各种依赖问题:
bash复制# 更新软件包列表和已安装的包
sudo apt update && sudo apt upgrade -y
# 安装基础工具链
sudo apt install -y vim curl wget net-tools gcc make build-essential
# 安装Nginx编译依赖
sudo apt install -y libpcre3 libpcre3-dev zlib1g zlib1g-dev openssl libssl-dev
特别注意:如果是CentOS/RHEL系统,需要使用yum命令替代apt,并且包名略有不同。例如pcre-devel代替libpcre3-dev。
1.3 防火墙配置
现代Linux系统通常都自带防火墙,我们需要正确配置它:
bash复制# 查看防火墙状态
sudo ufw status
# 开放必要端口
sudo ufw allow 22/tcp # SSH
sudo ufw allow 80/tcp # HTTP
sudo ufw allow 443/tcp # HTTPS
# 启用防火墙
sudo ufw enable
对于云服务器,除了系统防火墙,还需要在云服务商的控制台中配置安全组规则,开放相应端口。
2. Nginx的三种安装方式详解
2.1 系统包管理器安装(新手推荐)
这是最简单的安装方式,适合快速测试环境:
bash复制sudo apt install nginx -y
安装完成后,系统会自动:
- 创建nginx用户和组
- 设置好systemd服务
- 配置默认的网站目录和日志文件
验证安装:
bash复制nginx -v
systemctl status nginx
2.2 官方源安装(获取最新稳定版)
如果你想使用比系统仓库更新的版本,可以添加Nginx官方源:
bash复制# 安装必要工具
sudo apt install -y curl gnupg2 ca-certificates lsb-release ubuntu-keyring
# 导入Nginx签名密钥
curl https://nginx.org/keys/nginx_signing.key | gpg --dearmor | sudo tee /usr/share/keyrings/nginx-archive-keyring.gpg >/dev/null
# 添加Nginx官方源
echo "deb [signed-by=/usr/share/keyrings/nginx-archive-keyring.gpg] http://nginx.org/packages/ubuntu `lsb_release -cs` nginx" | sudo tee /etc/apt/sources.list.d/nginx.list
# 更新并安装
sudo apt update
sudo apt install nginx -y
2.3 源码编译安装(生产环境首选)
源码安装虽然复杂,但可以完全自定义Nginx的配置和模块:
bash复制# 下载最新稳定版
wget https://nginx.org/download/nginx-1.25.3.tar.gz
tar zxvf nginx-1.25.3.tar.gz
cd nginx-1.25.3
编译配置示例(根据需求调整):
bash复制./configure \
--prefix=/usr/local/nginx \
--user=nginx \
--group=nginx \
--with-http_ssl_module \
--with-http_v2_module \
--with-http_realip_module \
--with-http_gzip_static_module \
--with-http_stub_status_module \
--with-pcre \
--with-stream \
--with-threads
编译和安装:
bash复制make
sudo make install
配置systemd服务:
bash复制sudo vim /lib/systemd/system/nginx.service
写入以下内容:
ini复制[Unit]
Description=The NGINX HTTP and reverse proxy server
After=syslog.target network-online.target remote-fs.target nss-lookup.target
Wants=network-online.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 $MAINPID
PrivateTmp=true
[Install]
WantedBy=multi-user.target
启用服务:
bash复制sudo systemctl daemon-reload
sudo systemctl enable nginx
sudo systemctl start nginx
3. Nginx核心配置解析
3.1 配置文件结构
Nginx的配置文件采用模块化结构,主要分为几个部分:
code复制nginx.conf
├── 全局块 (Global Context)
├── events块 (Events Context)
└── http块 (HTTP Context)
├── server块 (Server Context)
│ ├── location块 (Location Context)
│ └── ...
└── ...
3.2 主配置文件详解
典型的nginx.conf结构:
nginx复制user www-data;
worker_processes auto;
pid /run/nginx.pid;
events {
worker_connections 1024;
multi_accept on;
use epoll;
}
http {
include /etc/nginx/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;
error_log /var/log/nginx/error.log warn;
sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 65;
gzip on;
gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;
include /etc/nginx/conf.d/*.conf;
include /etc/nginx/sites-enabled/*;
}
3.3 虚拟主机配置
每个网站应该有自己的配置文件,存放在/etc/nginx/sites-available/目录下,然后通过符号链接到/etc/nginx/sites-enabled/:
bash复制sudo vim /etc/nginx/sites-available/example.com
示例配置:
nginx复制server {
listen 80;
server_name example.com www.example.com;
root /var/www/example.com/html;
index index.html;
access_log /var/log/nginx/example.com.access.log;
error_log /var/log/nginx/example.com.error.log;
location / {
try_files $uri $uri/ =404;
}
location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
expires 30d;
access_log off;
}
}
启用站点:
bash复制sudo ln -s /etc/nginx/sites-available/example.com /etc/nginx/sites-enabled/
sudo nginx -t
sudo systemctl reload nginx
4. 生产环境实战配置
4.1 HTTPS配置
现代网站必须使用HTTPS。我们可以使用Let's Encrypt免费证书:
bash复制sudo apt install certbot python3-certbot-nginx
sudo certbot --nginx -d example.com -d www.example.com
Certbot会自动帮我们配置好Nginx的HTTPS设置。手动配置示例如下:
nginx复制server {
listen 443 ssl http2;
listen [::]:443 ssl http2;
server_name example.com www.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_ciphers 'ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256...';
ssl_prefer_server_ciphers on;
ssl_session_cache shared:SSL:10m;
ssl_session_timeout 10m;
# 其他配置...
}
server {
listen 80;
server_name example.com www.example.com;
return 301 https://$host$request_uri;
}
4.2 反向代理配置
Nginx最强大的功能之一就是反向代理。以下是代理Node.js应用的示例:
nginx复制location / {
proxy_pass http://localhost:3000;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
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;
proxy_cache_bypass $http_upgrade;
}
4.3 负载均衡配置
对于高流量网站,可以使用Nginx的负载均衡功能:
nginx复制upstream backend {
server backend1.example.com weight=5;
server backend2.example.com;
server backup.backend.example.com backup;
least_conn;
keepalive 32;
}
server {
location / {
proxy_pass http://backend;
# 其他代理配置...
}
}
5. 性能优化与安全加固
5.1 性能调优
nginx复制# worker进程数,通常设置为CPU核心数
worker_processes auto;
# 每个worker的最大连接数
events {
worker_connections 10240;
}
http {
# 开启高效文件传输
sendfile on;
tcp_nopush on;
# 连接超时设置
keepalive_timeout 30;
keepalive_requests 100;
# 客户端超时设置
client_body_timeout 10;
client_header_timeout 10;
send_timeout 10;
# 缓冲区优化
client_body_buffer_size 16K;
client_header_buffer_size 1k;
client_max_body_size 8m;
large_client_header_buffers 4 8k;
}
5.2 安全加固
nginx复制# 隐藏Nginx版本号
server_tokens off;
# 禁用不必要的HTTP方法
if ($request_method !~ ^(GET|HEAD|POST)$ ) {
return 405;
}
# 防止点击劫持
add_header X-Frame-Options "SAMEORIGIN";
# XSS防护
add_header X-XSS-Protection "1; mode=block";
# 内容安全策略
add_header Content-Security-Policy "default-src 'self'; script-src 'self' 'unsafe-inline' 'unsafe-eval' https://cdn.example.com; img-src 'self' data: https://*.example.com; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; font-src 'self' https://fonts.gstatic.com; frame-src 'none'; object-src 'none'";
# 禁止访问隐藏文件
location ~ /\. {
deny all;
access_log off;
log_not_found off;
}
6. 常见问题排查
6.1 502 Bad Gateway
这是最常见的Nginx错误之一,通常是因为后端服务没有运行或无法访问:
- 检查后端服务是否运行:
bash复制systemctl status your-backend-service
- 检查端口是否正确:
bash复制netstat -tulnp | grep 3000
- 检查Nginx错误日志:
bash复制tail -f /var/log/nginx/error.log
6.2 413 Request Entity Too Large
当上传大文件时可能会遇到这个问题,需要调整client_max_body_size:
nginx复制http {
client_max_body_size 100M;
}
6.3 性能问题排查
使用Nginx状态模块监控性能:
nginx复制location /nginx_status {
stub_status on;
access_log off;
allow 127.0.0.1;
deny all;
}
访问http://localhost/nginx_status会显示类似信息:
code复制Active connections: 3
server accepts handled requests
100 100 100
Reading: 0 Writing: 1 Waiting: 2
7. 高级功能与扩展
7.1 动态模块加载
Nginx 1.9.11+支持动态模块,可以在不重新编译的情况下添加模块:
bash复制# 查看已安装模块
nginx -V
# 安装额外模块
sudo apt install nginx-module-image-filter
然后在nginx.conf中加载:
nginx复制load_module modules/ngx_http_image_filter_module.so;
7.2 Lua脚本支持
通过OpenResty或ngx_http_lua_module可以为Nginx添加Lua脚本支持:
nginx复制location /hello {
default_type 'text/plain';
content_by_lua_block {
ngx.say("Hello, Lua!")
}
}
7.3 WebSocket代理
Nginx可以完美代理WebSocket连接:
nginx复制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;
}
8. 监控与维护
8.1 日志分析
使用goaccess等工具分析Nginx访问日志:
bash复制sudo apt install goaccess
goaccess /var/log/nginx/access.log --log-format=COMBINED
8.2 性能监控
使用Prometheus和Grafana监控Nginx:
- 启用Nginx状态模块
- 安装nginx-prometheus-exporter
- 配置Prometheus抓取指标
- 在Grafana中导入Nginx仪表板
8.3 定期维护
- 定期检查并更新Nginx版本
- 监控错误日志中的异常
- 定期备份配置文件
- 检查SSL证书到期时间并设置自动续期
9. 实际部署案例
9.1 静态网站部署
对于纯静态网站(如Vue/React构建的SPA),配置要点:
nginx复制server {
root /var/www/my-app/dist;
index index.html;
location / {
try_files $uri $uri/ /index.html;
}
location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg)$ {
expires 1y;
add_header Cache-Control "public, immutable";
}
}
9.2 PHP应用部署
对于WordPress等PHP应用:
nginx复制server {
location / {
try_files $uri $uri/ /index.php?$args;
}
location ~ \.php$ {
include fastcgi_params;
fastcgi_pass unix:/run/php/php8.1-fpm.sock;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_intercept_errors on;
}
}
9.3 微服务API网关
作为多个后端服务的统一入口:
nginx复制upstream auth_service {
server 10.0.1.10:8000;
}
upstream product_service {
server 10.0.1.20:8000;
}
server {
location /api/auth/ {
proxy_pass http://auth_service/;
}
location /api/products/ {
proxy_pass http://product_service/;
}
}
10. 最佳实践总结
经过多年的Nginx使用经验,我总结了以下最佳实践:
-
配置管理:
- 每个站点使用独立的配置文件
- 使用sites-available和sites-enabled目录结构
- 为每个配置添加详细注释
-
安全方面:
- 始终使用HTTPS并启用HTTP/2
- 限制不必要的HTTP方法
- 定期更新Nginx和系统补丁
-
性能优化:
- 根据服务器CPU核心数设置worker_processes
- 启用sendfile和tcp_nopush
- 合理配置静态资源缓存
-
维护建议:
- 修改配置前先备份
- 使用nginx -t测试配置语法
- 优先使用reload而非restart来加载新配置
-
监控与日志:
- 定期检查错误日志
- 为不同站点配置独立的访问日志
- 设置日志轮转防止日志文件过大
Nginx是一个极其强大且灵活的工具,掌握它的配置和优化技巧可以显著提升Web服务的性能和可靠性。希望本指南能帮助你从零开始构建一个高效、安全的Nginx服务器环境。