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 ├── proxy_params ├── ssl_params ├── fastcgi_params └── 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;
worker_processes auto;
pid /run/nginx.pid;
error_log /var/log/nginx/error.log warn;
include /etc/nginx/modules-enabled/*.conf;
events { worker_connections 1024; use epoll; multi_accept on; accept_mutex on; accept_mutex_delay 100ms; }
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; include /etc/nginx/mime.types; default_type application/octet-stream; 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 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
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 / { 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; } 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 { listen 5553 ssl http2; listen [::]:5553 ssl http2; server_name xunlei.mobufan.eu.org; ssl_certificate /etc/nginx/ssl/cert.pem; ssl_certificate_key /etc/nginx/ssl/key.pem; 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
| /var/www/html/
/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 │ ├── 50x.html │ └── assets/ │ ├── css/ │ ├── js/ │ ├── 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
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/
|
快速配置检查脚本
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| #!/bin/bash
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
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"
echo "" echo "🔝 最频繁访问的IP:" awk '{print $1}' "$LOG_FILE" | sort | uniq -c | sort -nr | head -10
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
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
openssl s_client -connect example.com:443 -servername example.com
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
|
定期备份: 修改配置前总是进行备份
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
| 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; }
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 -v
apt list --upgradable | grep nginx
|
通过这份详细的Nginx目录结构和配置指南,您应该能够更好地理解和管理Nginx服务器配置!🚀