Ubuntu 24.04 Nginx 安装与安全配置完整指南
Nginx 是一款高性能的 HTTP 和反向代理服务器,以其稳定性、丰富的功能集和低资源消耗而闻名。本文将详细介绍在 Ubuntu 24.04 上安装和配置 Nginx 的完整流程。
1. 系统准备与环境检查
1.1 系统更新
bash
# 更新包列表并升级系统
sudo apt update
sudo apt upgrade -y
# 安装必要的工具
sudo apt install -y \
curl \
wget \
vim \
net-tools \
htop \
ufw \
software-properties-common
1.2 检查系统信息
bash
# 查看 Ubuntu 版本
lsb_release -a
# 检查系统架构
uname -m
# 检查内存和磁盘空间
free -h
df -h
2. Nginx 安装
2.1 从官方仓库安装
bash
# 方法一:使用 Ubuntu 官方仓库
sudo apt install -y nginx
# 方法二:使用 Nginx 官方仓库(推荐,获取最新版本)
# 添加 Nginx 官方 GPG 密钥
curl -fsSL https://nginx.org/keys/nginx_signing.key | sudo gpg --dearmor -o /etc/apt/keyrings/nginx.gpg
# 添加 Nginx 官方仓库
echo "deb [signed-by=/etc/apt/keyrings/nginx.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 -y nginx
2.2 验证安装
bash
# 检查 Nginx 版本
nginx -v
nginx -V # 查看详细编译参数
# 检查 Nginx 服务状态
sudo systemctl status nginx
# 测试 Nginx 是否运行
curl -I 127.0.0.1
# 检查监听端口
sudo netstat -tulpn | grep nginx
sudo ss -tulpn | grep nginx
2.3 管理 Nginx 服务
bash
# 启动 Nginx
sudo systemctl start nginx
# 停止 Nginx
sudo systemctl stop nginx
# 重启 Nginx
sudo systemctl restart nginx
# 重新加载配置(不中断服务)
sudo systemctl reload nginx
# 查看 Nginx 进程
ps aux | grep nginx
# 设置开机自启
sudo systemctl enable nginx
3. Nginx 目录结构
bash
# 主要配置文件目录
/etc/nginx/
├── nginx.conf # 主配置文件
├── conf.d/ # 额外配置文件目录
├── sites-available/ # 可用的网站配置
├── sites-enabled/ # 启用的网站配置(符号链接)
├── modules-available/ # 可用模块
├── modules-enabled/ # 启用模块
├── snippets/ # 配置片段
└── mime.types # MIME 类型定义
# 网站文件目录
/var/www/html/ # 默认网站根目录
# 日志目录
/var/log/nginx/
├── access.log # 访问日志
└── error.log # 错误日志
# 其他重要目录
/usr/share/nginx/ # 文档和默认文件
/usr/lib/nginx/ # 模块目录
4. 基础配置
4.1 创建网站目录结构
bash
# 创建网站目录(示例:example.com)
sudo mkdir -p /var/www/example.com/{public,logs,backup}
# 设置权限
sudo chown -R www-data:www-data /var/www/example.com
sudo chmod -R 755 /var/www/example.com
# 创建测试页面
sudo tee /var/www/example.com/public/index.html <<EOF
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>欢迎来到 Example.com</title>
<style>
body { font-family: Arial, sans-serif; text-align: center; padding: 50px; }
h1 { color: #333; }
p { color: #666; }
.status {
background-color: #4CAF50;
color: white;
padding: 10px 20px;
border-radius: 5px;
display: inline-block;
}
</style>
</head>
<body>
<h1>🎉 欢迎访问 Example.com</h1>
<p>您的 Nginx 服务器已经成功运行!</p>
<div class="status">状态:正常运行</div>
<p><small>服务器时间:$(date)</small></p>
</body>
</html>
EOF
4.2 创建虚拟主机配置
bash
# 创建网站配置文件
sudo nano /etc/nginx/sites-available/example.com
添加以下配置:
nginx
# example.com 配置文件
server {
# 监听端口
listen 80;
listen [::]:80;
# 域名配置
server_name example.com www.example.com;
# 网站根目录
root /var/www/example.com/public;
# 默认索引文件
index index.html index.htm index.php;
# 访问日志
access_log /var/www/example.com/logs/access.log main buffer=32k flush=5s;
# 错误日志
error_log /var/www/example.com/logs/error.log warn;
# 基本安全头
add_header X-Frame-Options "SAMEORIGIN" always;
add_header X-Content-Type-Options "nosniff" always;
add_header X-XSS-Protection "1; mode=block" always;
# 文件上传大小限制
client_max_body_size 100M;
# 超时设置
client_body_timeout 12;
client_header_timeout 12;
keepalive_timeout 15;
send_timeout 10;
# Gzip 压缩配置
gzip on;
gzip_vary on;
gzip_min_length 1024;
gzip_types text/plain text/css text/xml text/javascript application/json application/javascript application/xml+rss application/atom+xml image/svg+xml;
# 静态文件缓存
location ~* \.(jpg|jpeg|png|gif|ico|css|js|svg|woff|woff2|ttf|eot)$ {
expires 365d;
add_header Cache-Control "public, immutable";
access_log off;
}
# 禁止访问隐藏文件
location ~ /\. {
deny all;
access_log off;
log_not_found off;
}
# 主 location 块
location / {
try_files $uri $uri/ =404;
# 安全限制
limit_req zone=one burst=10 nodelay;
limit_conn perip 10;
}
# 自定义 404 页面
error_page 404 /404.html;
location = /404.html {
internal;
root /var/www/example.com/public;
}
# 自定义 50x 错误页面
error_page 500 502 503 504 /50x.html;
location = /50x.html {
internal;
root /var/www/example.com/public;
}
}
4.3 启用网站配置
bash
# 创建符号链接启用配置
sudo ln -s /etc/nginx/sites-available/example.com /etc/nginx/sites-enabled/
# 删除默认配置
sudo rm /etc/nginx/sites-enabled/default
# 测试配置语法
sudo nginx -t
# 重新加载配置
sudo systemctl reload nginx
5. 安全加固配置
5.1 主配置文件加固
bash
# 备份原始配置
sudo cp /etc/nginx/nginx.conf /etc/nginx/nginx.conf.backup
# 编辑主配置
sudo nano /etc/nginx/nginx.conf
在 http 块中添加:
nginx
# 安全相关配置
http {
# 隐藏 Nginx 版本号
server_tokens off;
# 限制请求方法
limit_except GET POST PUT DELETE {
deny all;
}
# 请求限制配置
limit_req_zone $binary_remote_addr zone=one:10m rate=1r/s;
limit_conn_zone $binary_remote_addr zone=perip:10m;
limit_conn_zone $server_name zone=perserver:10m;
# 缓冲区大小限制(防止缓冲区溢出攻击)
client_body_buffer_size 1k;
client_header_buffer_size 1k;
client_max_body_size 1k;
large_client_header_buffers 2 1k;
# 禁用不必要的 HTTP 方法
if ($request_method !~ ^(GET|HEAD|POST)$) {
return 444;
}
# 防止点击劫持
add_header X-Frame-Options "SAMEORIGIN" always;
# 防止 MIME 类型嗅探
add_header X-Content-Type-Options "nosniff" always;
# XSS 保护
add_header X-XSS-Protection "1; mode=block" always;
# HSTS (HTTPS Strict Transport Security)
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains; preload" always;
# 内容安全策略 (CSP) - 根据实际情况调整
add_header Content-Security-Policy "default-src 'self'; script-src 'self' 'unsafe-inline' 'unsafe-eval'; style-src 'self' 'unsafe-inline'; img-src 'self' data: https:; font-src 'self';" always;
# 防止信息泄露
add_header Referrer-Policy "strict-origin-when-cross-origin" always;
add_header Permissions-Policy "geolocation=(), microphone=(), camera=()" always;
}
5.2 创建安全配置片段
bash
# 创建安全配置片段
sudo nano /etc/nginx/snippets/security-headers.conf
添加内容:
nginx
# 安全头部配置
add_header X-Frame-Options "SAMEORIGIN" always;
add_header X-Content-Type-Options "nosniff" always;
add_header X-XSS-Protection "1; mode=block" always;
add_header Referrer-Policy "strict-origin-when-cross-origin" always;
add_header Content-Security-Policy "default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; img-src 'self' data:;" always;
add_header Permissions-Policy "geolocation=(), microphone=(), camera=()" always;
# 防止点击劫持
add_header X-Frame-Options "DENY" always;
# HSTS - 仅在使用 HTTPS 时启用
# add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
5.3 创建请求限制配置
bash
sudo nano /etc/nginx/snippets/rate-limiting.conf
nginx
# 请求限制配置
limit_req_zone $binary_remote_addr zone=login:10m rate=5r/m;
limit_req_zone $binary_remote_addr zone=api:10m rate=10r/s;
limit_req_zone $binary_remote_addr zone=general:10m rate=100r/s;
# 连接数限制
limit_conn_zone $binary_remote_addr zone=addr:10m;
# DDoS 防护
limit_req_status 429;
limit_conn_status 429;
5.4 防止常见攻击
bash
sudo nano /etc/nginx/snippets/block-attacks.conf
nginx
# 阻止 SQL 注入攻击
location ~* "(\bunion\b.*\bselect|\bselect.*\bunion)" {
deny all;
}
# 阻止 XSS 攻击
location ~* "<script.*?>.*?</script>" {
deny all;
}
# 阻止目录遍历
location ~* "\.\./" {
deny all;
}
# 阻止敏感文件访问
location ~ /\.(env|git|svn|htaccess|htpasswd) {
deny all;
access_log off;
log_not_found off;
}
# 阻止常见漏洞扫描
location ~* "(nmap|nikto|sqlmap|wpscan|acunetix)" {
deny all;
}
# 阻止垃圾爬虫
if ($http_user_agent ~* (AhrefsBot|MJ12bot|SemrushBot|BLEXBot|rogerbot|dotbot)) {
return 403;
}
6. 性能优化
6.1 优化主配置文件
bash
sudo nano /etc/nginx/nginx.conf
在 http 块中添加:
nginx
# 性能优化配置
http {
# 工作进程配置
worker_processes auto;
worker_rlimit_nofile 65535;
# 事件模块配置
events {
worker_connections 4096;
multi_accept on;
use epoll;
}
# 连接优化
sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 65;
keepalive_requests 1000;
reset_timedout_connection on;
# 缓冲区优化
client_body_buffer_size 128k;
client_header_buffer_size 1k;
client_max_body_size 8m;
large_client_header_buffers 4 4k;
# 超时设置
client_body_timeout 10;
client_header_timeout 10;
send_timeout 10;
# Gzip 压缩优化
gzip on;
gzip_vary on;
gzip_min_length 256;
gzip_proxied any;
gzip_comp_level 6;
gzip_types
application/atom+xml
application/javascript
application/json
application/ld+json
application/manifest+json
application/rss+xml
application/vnd.geo+json
application/vnd.ms-fontobject
application/x-font-ttf
application/x-web-app-manifest+json
application/xhtml+xml
application/xml
font/opentype
image/bmp
image/svg+xml
image/x-icon
text/cache-manifest
text/css
text/plain
text/vcard
text/vnd.rim.location.xloc
text/vtt
text/x-component
text/x-cross-domain-policy;
# 文件缓存
open_file_cache max=200000 inactive=20s;
open_file_cache_valid 30s;
open_file_cache_min_uses 2;
open_file_cache_errors on;
# MIME 类型缓存
types_hash_max_size 2048;
}
6.2 启用 HTTP/2
在网站配置中添加:
nginx
server {
listen 443 ssl http2;
listen [::]:443 ssl http2;
# SSL 配置
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers ECDHE-RSA-AES256-GCM-SHA512:DHE-RSA-AES256-GCM-SHA512:ECDHE-RSA-AES256-GCM-SHA384:DHE-RSA-AES256-GCM-SHA384;
ssl_prefer_server_ciphers off;
ssl_session_cache shared:SSL:10m;
ssl_session_timeout 10m;
}
7. 防火墙配置
7.1 配置 UFW 防火墙
bash
# 查看 UFW 状态
sudo ufw status
# 启用 UFW(如果未启用)
sudo ufw enable
# 设置默认策略
sudo ufw default deny incoming
sudo ufw default allow outgoing
# 允许 SSH
sudo ufw allow ssh
sudo ufw allow 22/tcp
# 允许 HTTP/HTTPS
sudo ufw allow 80/tcp
sudo ufw allow 443/tcp
# 允许特定 IP 访问(可选)
sudo ufw allow from 192.168.1.0/24 to any port 22
sudo ufw allow from 203.0.113.0/24 to any port 80
# 速率限制
sudo ufw limit ssh/tcp
# 查看规则
sudo ufw status numbered
# 重新加载规则
sudo ufw reload
# 查看详细日志
sudo ufw logging on
7.2 配置 Nginx 内置限制
nginx
# 在 http 块中添加
http {
# 限制每个 IP 的连接数
limit_conn_zone $binary_remote_addr zone=limit_per_ip:10m;
limit_conn limit_per_ip 20;
# 限制请求速率
limit_req_zone $binary_remote_addr zone=one:10m rate=10r/s;
# 限制特定 location 的访问
location /login {
limit_req zone=one burst=5;
limit_conn limit_per_ip 5;
}
}
8. SSL/TLS 配置
8.1 安装 SSL 证书
bash
# 安装 Certbot(Let's Encrypt)
sudo apt install -y certbot python3-certbot-nginx
# 获取 SSL 证书
sudo certbot --nginx -d example.com -d www.example.com
# 自动续期测试
sudo certbot renew --dry-run
# 创建自动续期任务
sudo crontab -e
添加定时任务:
bash
# 每天凌晨 3 点检查证书续期
0 3 * * * /usr/bin/certbot renew --quiet --post-hook "systemctl reload nginx"
8.2 配置 SSL
nginx
server {
listen 443 ssl http2;
listen [::]:443 ssl http2;
server_name example.com www.example.com;
# SSL 证书路径
ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
# SSL 协议配置
ssl_protocols TLSv1.2 TLSv1.3;
ssl_prefer_server_ciphers on;
# SSL 加密套件
ssl_ciphers ECDHE-RSA-AES256-GCM-SHA512:DHE-RSA-AES256-GCM-SHA512:ECDHE-RSA-AES256-GCM-SHA384:DHE-RSA-AES256-GCM-SHA384;
# SSL 会话缓存
ssl_session_cache shared:SSL:10m;
ssl_session_timeout 10m;
ssl_session_tickets off;
# OCSP 装订
ssl_stapling on;
ssl_stapling_verify on;
ssl_trusted_certificate /etc/letsencrypt/live/example.com/chain.pem;
# DH 参数(生成:openssl dhparam -out /etc/nginx/dhparam.pem 4096)
ssl_dhparam /etc/nginx/dhparam.pem;
# HSTS
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains; preload" always;
# 强制 HTTPS 重定向
if ($scheme != "https") {
return 301 https://$server_name$request_uri;
}
}
9. 日志管理
9.1 日志配置
nginx
# 访问日志格式
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for" '
'$request_time $upstream_response_time';
log_format json_analytics escape=json '{'
'"msec": "$msec", ' # request unixtime in seconds with a milliseconds resolution
'"connection": "$connection", ' # connection serial number
'"connection_requests": "$connection_requests", ' # number of requests made in connection
'"pid": "$pid", ' # process pid
'"request_id": "$request_id", ' # the unique request id
'"request_length": "$request_length", ' # request length (including headers and body)
'"remote_addr": "$remote_addr", ' # client IP
'"remote_user": "$remote_user", ' # client HTTP username
'"remote_port": "$remote_port", ' # client port
'"time_local": "$time_local", ' # local time in the Common Log Format
'"time_iso8601": "$time_iso8601", ' # local time in the ISO 8601 standard format
'"request": "$request", ' # full path no arguments if the request
'"request_uri": "$request_uri", ' # full path and arguments if the request
'"args": "$args", ' # args
'"status": "$status", ' # response status code
'"body_bytes_sent": "$body_bytes_sent", ' # the number of body bytes exclude headers sent to a client
'"bytes_sent": "$bytes_sent", ' # the number of bytes sent to a client
'"http_referer": "$http_referer", ' # HTTP referer
'"http_user_agent": "$http_user_agent", ' # user agent
'"http_x_forwarded_for": "$http_x_forwarded_for", ' # http_x_forwarded_for
'"http_host": "$http_host", ' # the request Host: header
'"server_name": "$server_name", ' # the name of the vhost serving the request
'"request_time": "$request_time", ' # request processing time in seconds with msec resolution
'"upstream": "$upstream_addr", ' # upstream backend server for proxied requests
'"upstream_connect_time": "$upstream_connect_time", ' # upstream handshake time incl. TLS
'"upstream_header_time": "$upstream_header_time", ' # time spent receiving upstream headers
'"upstream_response_time": "$upstream_response_time", ' # time spend receiving upstream body
'"upstream_response_length": "$upstream_response_length", ' # upstream response length
'"upstream_cache_status": "$upstream_cache_status", ' # cache HIT/MISS where applicable
'"ssl_protocol": "$ssl_protocol", ' # TLS protocol
'"ssl_cipher": "$ssl_cipher", ' # TLS cipher
'"scheme": "$scheme", ' # http or https
'"request_method": "$request_method", ' # request method
'"server_protocol": "$server_protocol", ' # request protocol, like HTTP/1.1 or HTTP/2.0
'"pipe": "$pipe", ' # "p" if request was pipelined, "." otherwise
'"gzip_ratio": "$gzip_ratio", ' # gzip compression ratio of the response
'"http_cf_ray": "$http_cf_ray"'
'}';
# 使用日志格式
access_log /var/log/nginx/access.log main buffer=32k flush=5s;
error_log /var/log/nginx/error.log warn;
9.2 日志轮转
bash
# 配置 logrotate
sudo nano /etc/logrotate.d/nginx
bash
/var/log/nginx/*.log {
daily
missingok
rotate 14
compress
delaycompress
notifempty
create 640 www-data adm
sharedscripts
postrotate
if [ -f /var/run/nginx.pid ]; then
kill -USR1 `cat /var/run/nginx.pid`
fi
endscript
}
10. 监控与维护
10.1 安装监控工具
bash
# 安装 Nginx Amplify(商业版,有免费额度)
# 或者使用开源替代方案
# 安装 GoAccess(实时日志分析)
sudo apt install -y goaccess
# 生成 HTML 报告
goaccess /var/log/nginx/access.log --log-format=COMBINED -o /var/www/html/report.html
# 实时监控
goaccess /var/log/nginx/access.log --log-format=COMBINED --real-time-html
10.2 健康检查配置
nginx
# 健康检查端点
location /nginx_status {
stub_status on;
access_log off;
allow 127.0.0.1;
allow 192.168.1.0/24;
deny all;
}
location /health {
access_log off;
return 200 "healthy\n";
add_header Content-Type text/plain;
}
10.3 备份脚本
bash
# 创建备份脚本
sudo nano /usr/local/bin/backup_nginx.sh
bash
#!/bin/bash
# Nginx 配置备份脚本
BACKUP_DIR="/backup/nginx"
DATE=$(date +%Y%m%d_%H%M%S)
# 创建备份目录
mkdir -p $BACKUP_DIR/$DATE
# 备份配置文件
cp -r /etc/nginx $BACKUP_DIR/$DATE/
# 备份网站文件
cp -r /var/www $BACKUP_DIR/$DATE/
# 备份日志(可选)
# cp -r /var/log/nginx $BACKUP_DIR/$DATE/
# 创建压缩包
tar -czf $BACKUP_DIR/nginx_backup_$DATE.tar.gz -C $BACKUP_DIR/$DATE .
# 清理旧备份(保留最近7天)
find $BACKUP_DIR -name "*.tar.gz" -mtime +7 -delete
# 清理临时目录
rm -rf $BACKUP_DIR/$DATE
echo "备份完成:$BACKUP_DIR/nginx_backup_$DATE.tar.gz"
bash
# 设置权限
sudo chmod +x /usr/local/bin/backup_nginx.sh
# 添加到定时任务
sudo crontab -e
添加:
bash
# 每天凌晨2点备份
0 2 * * * /usr/local/bin/backup_nginx.sh
11. 故障排除
11.1 常用诊断命令
bash
# 检查配置语法
sudo nginx -t
# 查看 Nginx 错误日志
sudo tail -f /var/log/nginx/error.log
# 查看访问日志
sudo tail -f /var/log/nginx/access.log
# 查看 Nginx 进程
ps aux | grep nginx
# 检查端口监听
sudo netstat -tulpn | grep :80
sudo netstat -tulpn | grep :443
# 测试配置更改
sudo nginx -s reload
# 强制停止
sudo pkill -9 nginx
# 查看系统资源
htop
free -h
11.2 性能测试
bash
# 安装压力测试工具
sudo apt install -y apache2-utils
# 压力测试
ab -n 1000 -c 100 http://localhost/
# 更多工具
sudo apt install -y siege wrk
12. 生产环境建议
12.1 安全清单
- 隐藏 Nginx 版本号
- 配置适当的请求限制
- 启用安全头部
- 配置 SSL/TLS
- 设置防火墙规则
- 定期更新系统和软件包
- 禁用不必要的 HTTP 方法
- 配置适当的文件权限
12.2 性能清单
- 启用 Gzip 压缩
- 配置浏览器缓存
- 优化工作进程数
- 启用 HTTP/2
- 配置连接池
- 优化缓冲区大小
12.3 监控清单
- 配置日志轮转
- 设置健康检查端点
- 配置备份策略
- 安装监控工具
- 设置告警阈值
总结
通过本教程,你可以成功的在 Ubuntu 24.04 上部署一个安全、高性能的 Nginx 服务器。并且你将拥有:
✓ 完全配置的 Nginx 服务器
✓ 安全加固配置
✓ 性能优化设置
✓ SSL/TLS 加密
✓ 防火墙规则
✓ 监控和维护工具
✓ 备份策略
这个配置可以作为生产环境的坚实基础,根据实际业务需求进行适当调整即可。
生产环境注意事项:
- 定期更新 Nginx 和安全补丁
- 监控服务器资源和性能指标
- 定期审计安全配置
- 保持备份的完整性和可恢复性
- 根据业务增长调整配置参数