Nginx 目录结构与配置文件详解 🗂️ 📖 目录导航 🌟 Ngin
Nginx 目录结构与配置文件详解 🗂️
📖 目录导航
🌟 Nginx 配置文件架构概述
Nginx 采用模块化的配置文件结构,让您能够轻松管理和维护复杂的服务器配置。Nginx 的配置系统具有以下特点:
- 🏗️ 模块化设计:配置文件分为多个部分,便于管理和维护
- 🔧 层次结构:采用指令块的方式组织配置,清晰易懂
- ⚡ 高性能:配置文件在启动时加载,运行时无需重新解析
- 🔒 安全性:支持多种安全配置选项和访问控制
- 📊 灵活性:支持条件判断、变量使用和自定义配置
📋 配置文件结构总览
1
2
3
4
5
6
7
8
9
10
11
|
/etc/nginx/
├── nginx.conf # 主配置文件
├── conf.d/ # 自定义配置文件目录
├── sites-available/ # 可用站点配置
├── sites-enabled/ # 启用站点配置(符号链接)
├── modules-enabled/ # 启用模块配置
├── mime.types # MIME类型映射
├── proxy_params # 代理参数配置
├── ssl_params # SSL参数配置
├── fastcgi_params # FastCGI参数配置
└── snippets/ # 配置片段
|
关键目录说明
- nginx.conf: 主配置文件,包含全局设置和引入其他配置
- conf.d/: 存放自定义配置文件,通常按功能分类
- sites-available/: 所有可用的站点配置文件
- sites-enabled/: 实际启用的站点配置(符号链接到 sites-available)
- snippets/: 存放可重用的配置片段
🔧 一、Nginx 主配置文件
主配置文件位置
优化后的主配置文件示例
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
|
# 运行用户和组
user www-data;
# 工作进程数(建议设置为CPU核心数)
worker_processes auto;
# PID文件位置
pid /run/nginx.pid;
# 错误日志设置
error_log /var/log/nginx/error.log warn;
# 加载动态模块
include /etc/nginx/modules-enabled/*.conf;
# 事件模块配置
events {
# 每个工作进程的最大连接数
worker_connections 1024;
# 使用epoll高效处理连接(Linux)
use epoll;
# 多连接接受处理
multi_accept on;
# 连接处理优化
accept_mutex on;
accept_mutex_delay 100ms;
}
# HTTP模块配置
http {
# 基本设置
sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 65;
types_hash_max_size 2048;
server_tokens off;
# 服务器名称哈希表大小
server_names_hash_bucket_size 64;
server_names_hash_max_size 2048;
# MIME类型配置
include /etc/nginx/mime.types;
default_type application/octet-stream;
# SSL配置
ssl_protocols TLSv1.2 TLSv1.3;
ssl_prefer_server_ciphers on;
ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256;
ssl_session_cache shared:SSL:10m;
ssl_session_timeout 10m;
ssl_session_tickets off;
ssl_stapling on;
ssl_stapling_verify on;
# 解析器配置
resolver 8.8.8.8 1.1.1.1 valid=300s;
resolver_timeout 5s;
# 日志格式
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
log_format json escape=json '{"time": "$time_local", '
'"remote_addr": "$remote_addr", '
'"remote_user": "$remote_user", '
'"request": "$request", '
'"status": "$status", '
'"body_bytes_sent": "$body_bytes_sent", '
'"http_referer": "$http_referer", '
'"http_user_agent": "$http_user_agent", '
'"http_x_forwarded_for": "$http_x_forwarded_for"}';
access_log /var/log/nginx/access.log main;
# Gzip压缩
gzip on;
gzip_vary on;
gzip_min_length 1024;
gzip_proxied any;
gzip_comp_level 6;
gzip_types text/plain text/css text/xml text/javascript
application/json application/javascript application/xml+rss
application/atom+xml image/svg+xml;
# 文件缓存优化
open_file_cache max=1000 inactive=20s;
open_file_cache_valid 30s;
open_file_cache_min_uses 2;
open_file_cache_errors on;
# 客户端限制
client_max_body_size 100M;
client_body_buffer_size 128k;
client_header_buffer_size 1k;
large_client_header_buffers 4 4k;
# 超时设置
client_body_timeout 12;
client_header_timeout 12;
send_timeout 10;
# 包含其他配置
include /etc/nginx/conf.d/*.conf;
include /etc/nginx/sites-enabled/*;
}
|
配置文件管理命令
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
# 查看主配置
cat /etc/nginx/nginx.conf
# 编辑配置
sudo nano /etc/nginx/nginx.conf
# 备份配置
sudo cp /etc/nginx/nginx.conf /etc/nginx/nginx.conf.backup.$(date +%Y%m%d)
# 清理注释和空行(生产环境谨慎使用)
grep -Ev '#|^$' /etc/nginx/nginx.conf.backup | sudo tee /etc/nginx/nginx.conf
# 检查配置语法
sudo nginx -t
# 重新加载配置
sudo nginx -s reload
# 完全重启Nginx
sudo systemctl restart nginx
|
🌐 二、Nginx 站点配置文件
默认站点配置位置
1
2
|
/etc/nginx/sites-available/default
/etc/nginx/sites-enabled/default
|
优化后的默认站点配置
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
|
server {
# 监听端口配置
listen 80 default_server;
listen [::]:80 default_server;
# 服务器名称(可使用通配符)
server_name _;
# 根目录设置
root /var/www/html;
# 默认索引文件
index index.html index.htm index.nginx-debian.html;
# 访问日志
access_log /var/log/nginx/host.access.log main;
# 错误日志
error_log /var/log/nginx/host.error.log warn;
# 根路径处理
location / {
# 尝试提供请求的文件,否则返回404
try_files $uri $uri/ =404;
# 安全头部
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 "no-referrer-when-downgrade" always;
}
# 静态文件缓存设置
location ~* \.(jpg|jpeg|png|gif|ico|css|js|svg|woff|woff2|ttf|eot)$ {
expires 30d;
add_header Cache-Control "public, immutable";
add_header Access-Control-Allow-Origin "*";
# 日志记录关闭
access_log off;
log_not_found off;
}
# 禁止访问隐藏文件
location ~ /\. {
deny all;
access_log off;
log_not_found off;
}
# 禁止访问常见敏感文件
location ~* (\.env|composer\.json|composer\.lock|package\.json|package-lock\.json|\.git|\.svn|\.htaccess) {
deny all;
access_log off;
log_not_found off;
}
# 自定义错误页面
error_page 404 /404.html;
location = /404.html {
internal;
root /var/www/html;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
internal;
root /var/www/html;
}
# PHP处理(如果需要)
location ~ \.php$ {
include snippets/fastcgi-php.conf;
fastcgi_pass unix:/var/run/php/php8.1-fpm.sock;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
}
|
站点配置管理
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
# 启用站点(创建符号链接)
sudo ln -s /etc/nginx/sites-available/example.com /etc/nginx/sites-enabled/
# 禁用站点(删除符号链接)
sudo rm /etc/nginx/sites-enabled/example.com
# 列出所有可用站点
ls -la /etc/nginx/sites-available/
# 列出所有启用站点
ls -la /etc/nginx/sites-enabled/
# 测试站点配置
sudo nginx -t
# 重新加载配置(不中断服务)
sudo nginx -s reload
|
🎯 三、自定义配置文件
自定义配置目录
反向代理配置示例(xunlei.conf)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
|
# 迅雷反向代理配置
server {
# SSL监听端口
listen 5553 ssl http2;
listen [::]:5553 ssl http2;
# 域名设置
server_name xunlei.mobufan.eu.org;
# SSL证书配置
ssl_certificate /etc/nginx/ssl/cert.pem;
ssl_certificate_key /etc/nginx/ssl/key.pem;
# SSL优化配置
ssl_session_cache shared:SSL:10m;
ssl_session_timeout 10m;
ssl_session_tickets off;
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384;
ssl_prefer_server_ciphers on;
# 安全头设置
add_header X-Frame-Options DENY;
add_header X-Content-Type-Options nosniff;
add_header X-XSS-Protection "1; mode=block";
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
add_header Referrer-Policy "strict-origin-when-cross-origin" always;
# 访问日志
access_log /var/log/nginx/xunlei.access.log main;
error_log /var/log/nginx/xunlei.error.log warn;
# 反向代理设置
location / {
# 后端服务器地址
proxy_pass http://10.10.10.245:2345;
# 代理头设置
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_set_header X-Forwarded-Host $host;
proxy_set_header X-Forwarded-Port $server_port;
# 超时设置
proxy_connect_timeout 30s;
proxy_send_timeout 30s;
proxy_read_timeout 30s;
# 缓冲设置
proxy_buffering on;
proxy_buffer_size 4k;
proxy_buffers 8 4k;
proxy_busy_buffers_size 8k;
# 文件上传大小限制
client_max_body_size 20G;
}
# 健康检查端点
location /nginx_status {
stub_status on;
access_log off;
allow 127.0.0.1;
allow 10.10.10.0/24;
deny all;
}
# 基础认证保护(可选)
location /admin {
auth_basic "Restricted Area";
auth_basic_user_file /etc/nginx/.htpasswd;
# 代理设置同上
proxy_pass http://10.10.10.245:2345;
include /etc/nginx/proxy_params;
}
}
|
自定义配置管理
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
# 创建新的配置文件
sudo nano /etc/nginx/conf.d/myapp.conf
# 检查配置语法
sudo nginx -t -c /etc/nginx/conf.d/myapp.conf
# 重载配置
sudo nginx -s reload
# 查看所有自定义配置
ls -la /etc/nginx/conf.d/
# 禁用配置文件(重命名)
sudo mv /etc/nginx/conf.d/myapp.conf /etc/nginx/conf.d/myapp.conf.disabled
# 启用配置文件
sudo mv /etc/nginx/conf.d/myapp.conf.disabled /etc/nginx/conf.d/myapp.conf
|
📁 四、Nginx 网页目录结构
默认网页目录
1
2
3
4
5
|
# Ubuntu/Debian 系统
/var/www/html/
# CentOS/RHEL 系统
/usr/share/nginx/html/
|
目录结构示例
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
/var/www/
├── html/ # 默认网站根目录
│ ├── index.html # 默认首页
│ ├── 404.html # 404错误页面
│ ├── 50x.html # 50x错误页面
│ └── assets/ # 静态资源目录
│ ├── css/ # CSS样式文件
│ ├── js/ # JavaScript文件
│ ├── images/ # 图片文件
│ └── fonts/ # 字体文件
├── example.com/ # 虚拟主机目录
│ └── public_html/ # 网站根目录
└── logs/ # 网站日志目录(可选)
├── access.log # 访问日志
└── error.log # 错误日志
|
目录管理命令
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
# 进入网页目录
cd /var/www/html/
# 查看目录内容
ls -la
# 设置正确的权限
sudo chown -R www-data:www-data /var/www/html/
sudo chmod -R 755 /var/www/html/
# 创建新的站点目录
sudo mkdir -p /var/www/example.com/public_html
# 设置适当的权限
sudo chown -R www-data:www-data /var/www/example.com/
sudo chmod -R 755 /var/www/example.com/
# 创建日志目录
sudo mkdir -p /var/log/nginx/example.com/
sudo chown -R www-data:www-data /var/log/nginx/example.com/
|
🛠️ 五、实用管理脚本
配置备份脚本
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
#!/bin/bash
# nginx-backup.sh
BACKUP_DIR="/backup/nginx/$(date +%Y%m%d)"
mkdir -p $BACKUP_DIR
echo "🔧 开始备份Nginx配置..."
# 备份所有配置
cp -r /etc/nginx/ $BACKUP_DIR/
cp /var/log/nginx/error.log $BACKUP_DIR/
# 备份网站内容
tar -czf $BACKUP_DIR/www-backup.tar.gz /var/www/html/
echo "✅ Nginx配置已备份到: $BACKUP_DIR"
echo "📊 备份内容:"
ls -la $BACKUP_DIR/
# 添加到cron定期执行
# 0 2 * * * /path/to/nginx-backup.sh
|
快速配置检查脚本
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
#!/bin/bash
# nginx-check.sh
echo "🔍 检查Nginx配置..."
sudo nginx -t
echo ""
echo "📊 当前运行状态:"
sudo systemctl status nginx --no-pager -l
echo ""
echo "🌐 监听端口:"
sudo netstat -tulnp | grep nginx
echo ""
echo "📈 工作进程:"
ps aux | grep nginx | grep -v grep
echo ""
echo "📂 配置文件包含:"
sudo nginx -T 2>/dev/null | grep -E "(include|conf.d|sites)" | head -10
|
日志分析脚本
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
|
#!/bin/bash
# nginx-log-analyzer.sh
LOG_FILE="${1:-/var/log/nginx/access.log}"
if [ ! -f "$LOG_FILE" ]; then
echo "❌ 日志文件不存在: $LOG_FILE"
exit 1
fi
echo "📊 分析日志文件: $LOG_FILE"
echo "=========================================="
# 总请求数
TOTAL_REQUESTS=$(wc -l < "$LOG_FILE")
echo "总请求数: $TOTAL_REQUESTS"
# 最频繁的IP
echo ""
echo "🔝 最频繁访问的IP:"
awk '{print $1}' "$LOG_FILE" | sort | uniq -c | sort -nr | head -10
# 最频繁的URL
echo ""
echo "🔝 最频繁访问的URL:"
awk '{print $7}' "$LOG_FILE" | sort | uniq -c | sort -nr | head -10
# 响应状态码统计
echo ""
echo "📊 响应状态码统计:"
awk '{print $9}' "$LOG_FILE" | sort | uniq -c | sort -nr
# 带宽使用
echo ""
echo "💾 带宽使用情况:"
awk '{sum += $10} END {print "总传输数据: " sum/1024/1024 " MB"}' "$LOG_FILE"
|
🔍 六、故障排查指南
常见问题排查
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
# 检查错误日志
sudo tail -f /var/log/nginx/error.log
# 检查访问日志
sudo tail -f /var/log/nginx/access.log
# 检查配置包含关系
sudo nginx -T | grep -E "(include|conf.d|sites)"
# 检查端口冲突
sudo lsof -i :80 -i :443
# 检查文件权限
namei -l /var/www/html/index.html
# 检查SELinux状态
getenforce
sestatus
# 检查防火墙设置
sudo ufw status
sudo firewall-cmd --list-all
|
性能监控
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
# 实时连接监控
sudo ngxtop
# 查看工作进程
ps aux | grep nginx
# 监控资源使用
top -p $(pgrep -d',' nginx)
# 查看连接状态
netstat -an | grep :80 | awk '{print $6}' | sort | uniq -c
# 实时监控访问日志
tail -f /var/log/nginx/access.log | awk '{print $1, $4, $7, $9}'
# 检查缓慢请求
sudo grep "upstream timed out" /var/log/nginx/error.log
|
调试技巧
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
# 详细调试模式
sudo nginx -t -c /etc/nginx/nginx.conf -g "daemon off; master_process off;"
# 检查特定配置
sudo nginx -T | grep -A 10 -B 5 "server_name example.com"
# 测试重定向
curl -I http://example.com
# 测试SSL连接
openssl s_client -connect example.com:443 -servername example.com
# 检查HTTP头
curl -I -H "Host: example.com" http://localhost
# 压力测试
ab -n 1000 -c 100 http://example.com/
|
🎯 最佳实践建议
-
模块化配置: 将不同功能分离到不同的配置文件中
1
2
3
4
5
6
7
8
9
10
|
# 按功能分离配置
/etc/nginx/
├── conf.d/
│ ├── security.conf # 安全配置
│ ├── compression.conf # 压缩配置
│ ├── caching.conf # 缓存配置
│ └── logging.conf # 日志配置
└── sites-available/
├── example.com # 主站点
└── api.example.com # API站点
|
-
定期备份: 修改配置前总是进行备份
1
2
3
4
5
6
7
8
|
# 创建配置备份
sudo cp /etc/nginx/nginx.conf /etc/nginx/nginx.conf.backup.$(date +%Y%m%d)
# 使用版本控制
cd /etc/nginx
sudo git init
sudo git add .
sudo git commit -m "Initial nginx configuration"
|
-
版本控制: 对配置文件使用Git进行版本管理
1
2
3
4
5
6
7
8
|
# 初始化Git仓库
sudo git init /etc/nginx
# 添加所有配置文件
sudo git add /etc/nginx/
# 提交更改
sudo git commit -m "Update nginx configuration"
|
-
安全加固: 定期更新和检查安全配置
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
# 安全头部配置
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 Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
# 隐藏服务器信息
server_tokens off;
# 限制请求大小
client_max_body_size 10M;
# 限制请求方法
if ($request_method !~ ^(GET|HEAD|POST)$) {
return 405;
}
|
-
性能监控: 设置监控告警,及时发现性能问题
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
# 安装监控工具
sudo apt-get install nginx-module-njs
# 启用状态模块
location /nginx_status {
stub_status on;
access_log off;
allow 127.0.0.1;
deny all;
}
# 使用Prometheus监控
location /metrics {
stub_status on;
access_log off;
}
|
-
日志管理: 合理配置日志轮转和存储
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
# 配置日志轮转
sudo nano /etc/logrotate.d/nginx
# 示例配置
/var/log/nginx/*.log {
daily
missingok
rotate 14
compress
delaycompress
notifempty
create 0640 www-data adm
sharedscripts
postrotate
if [ -f /var/run/nginx.pid ]; then
kill -USR1 `cat /var/run/nginx.pid`
fi
endscript
}
|
-
定期更新: 保持Nginx和系统的最新状态
1
2
3
4
5
6
7
8
|
# 更新系统包
sudo apt update && sudo apt upgrade -y
# 检查Nginx版本
nginx -v
# 查看可用更新
apt list --upgradable | grep nginx
|
通过这份详细的Nginx目录结构和配置指南,您应该能够更好地理解和管理Nginx服务器配置!🚀