切换导航
人间一铺后台系统
Ubuntu 22
Ufw 配置防火墙
Lnmp 多版本PHP
Nginx 安装及配置
Mysql 安装及配置
Php 安装及配置
Redis 安装及配置
Svn 安装及配置
Frp 安装及配置
OpenVPN 安装及配置
搜索结果
没有相关内容~~
Nginx 安装及配置
最新修改于
2025-12-25 16:26
## 安装 Nginx ### 方法一:使用 APT 安装(推荐) ```bash # 更新包列表 sudo apt update # 安装 Nginx sudo apt install nginx # 验证安装 nginx -v ``` ### 方法二:安装最新版本 ```bash # 添加 Nginx 官方仓库 sudo apt install 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 # 添加稳定版仓库 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 # 安装 Nginx sudo apt update sudo apt install nginx ``` ## 基本管理命令 ```bash # 启动 Nginx sudo systemctl start nginx # 停止 Nginx sudo systemctl stop nginx # 重启 Nginx sudo systemctl restart nginx # 重新加载配置(不中断服务) sudo systemctl reload nginx # 检查状态 sudo systemctl status nginx # 设置开机自启 sudo systemctl enable nginx # 禁止开机自启 sudo systemctl disable nginx # 测试配置文件语法 sudo nginx -t # 查看 Nginx 进程 ps aux | grep nginx ``` ## 目录结构 ```bash # 主要配置文件目录 /etc/nginx/ ├── nginx.conf # 主配置文件 ├── sites-available/ # 可用站点配置 ├── sites-enabled/ # 已启用站点配置(符号链接) ├── conf.d/ # 额外配置 ├── modules-available/ # 可用模块 ├── modules-enabled/ # 已启用模块 ├── snippets/ # 可复用的配置片段 # 网站文件目录 /var/www/html/ # 默认网站根目录 # 日志目录 /var/log/nginx/ ├── access.log # 访问日志 └── error.log # 错误日志 # PID 文件 /var/run/nginx.pid ``` ## 基本配置 ### 1. 主配置文件结构 ```bash sudo nano /etc/nginx/nginx.conf ``` ### 2. 常用全局配置 ```nginx # /etc/nginx/nginx.conf user www-data; # 运行用户 worker_processes auto; # 工作进程数(通常设为CPU核心数) pid /run/nginx.pid; # PID文件位置 # 事件模块配置 events { worker_connections 1024; # 每个工作进程最大连接数 multi_accept on; # 同时接受多个连接 use epoll; # 使用epoll事件模型(Linux) } # HTTP模块配置 http { # 基本设置 sendfile on; # 启用sendfile零拷贝 tcp_nopush on; # 优化数据包发送 tcp_nodelay on; # 禁用Nagle算法 keepalive_timeout 65; # 保持连接超时时间 types_hash_max_size 2048; # MIME类型哈希表大小 # MIME类型 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; # Gzip压缩 gzip on; gzip_vary on; 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; # 包含其他配置文件 include /etc/nginx/conf.d/*.conf; include /etc/nginx/sites-enabled/*; } ``` ## 虚拟主机配置 ### 1. 创建网站配置 ```bash # 在 sites-available 中创建配置文件 sudo nano /etc/nginx/sites-available/example.com ``` ### 2. 基础站点配置 ```nginx server { listen 80; listen [::]:80; # 域名 server_name example.com www.example.com; # 网站根目录 root /var/www/example.com/html; # 索引文件 index index.html index.htm index.php; # 访问日志 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; add_header Cache-Control "public, immutable"; } # 禁止访问隐藏文件 location ~ /\. { deny all; } } ``` ### 3. 启用网站 ```bash # 创建符号链接 sudo ln -s /etc/nginx/sites-available/example.com /etc/nginx/sites-enabled/ # 测试配置 sudo nginx -t # 重新加载 Nginx sudo systemctl reload nginx ``` ### 4. 禁用网站 ```bash sudo rm /etc/nginx/sites-enabled/example.com sudo systemctl reload nginx ``` ## PHP 支持(PHP-FPM) ### 1. 安装 PHP-FPM ```bash # 安装 PHP 和 PHP-FPM sudo apt install php-fpm php-cli php-mysql php-curl php-gd php-mbstring php-xml php-xmlrpc php-zip # 检查 PHP-FPM 状态 sudo systemctl status php-fpm # 查看 PHP-FPM 套接字路径 ls /run/php/php*-fpm.sock ``` ### 2. Nginx 配置 PHP 支持 ```nginx server { # ... 其他配置 ... # PHP 处理 location ~ \.php$ { include snippets/fastcgi-php.conf; # PHP-FPM 套接字路径 fastcgi_pass unix:/run/php/php8.1-fpm.sock; # 或使用 TCP 连接 # fastcgi_pass 127.0.0.1:9000; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; include fastcgi_params; } # 拒绝访问敏感文件 location ~ /(\.|vendor|composer\.json|composer\.lock|README\.md|\.git) { deny all; } } ``` ## SSL/TLS 配置(HTTPS) ### 1. 使用 Let's Encrypt(免费证书) ```bash # 安装 Certbot sudo apt install certbot python3-certbot-nginx # 获取并安装证书 sudo certbot --nginx -d example.com -d www.example.com # 自动续期测试 sudo certbot renew --dry-run ``` ### 2. 手动 SSL 配置 ```nginx server { listen 443 ssl http2; listen [::]:443 ssl http2; server_name example.com www.example.com; # SSL 证书路径 ssl_certificate /etc/ssl/certs/example.com.crt; ssl_certificate_key /etc/ssl/private/example.com.key; # 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; # HSTS 头 add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always; # 其他配置... } # HTTP 重定向到 HTTPS server { listen 80; listen [::]:80; server_name example.com www.example.com; return 301 https://$server_name$request_uri; } ``` ## 反向代理配置 ### 1. 反向代理到本地应用 ```nginx server { listen 80; server_name app.example.com; location / { proxy_pass http://localhost:3000; # Node.js 应用 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; } } ``` ### 2. 负载均衡配置 ```nginx # 上游服务器组 upstream backend { least_conn; # 最少连接算法 server backend1.example.com:80 weight=3; server backend2.example.com:80; server backend3.example.com:80; # 健康检查 server backup1.example.com:80 backup; server backup2.example.com:80 backup; } server { location / { proxy_pass http://backend; # 代理头 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_connect_timeout 5s; proxy_send_timeout 10s; proxy_read_timeout 10s; } } ``` ## 性能优化 ### 1. 调整工作进程 ```nginx # /etc/nginx/nginx.conf worker_processes auto; # 自动设置为CPU核心数 worker_rlimit_nofile 65535; # 文件描述符限制 events { worker_connections 4096; # 增加每个工作进程的连接数 use epoll; # Linux 使用 epoll multi_accept on; } ``` ### 2. 缓存配置 ```nginx # 代理缓存 proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=my_cache:10m max_size=10g inactive=60m use_temp_path=off; server { location / { proxy_cache my_cache; proxy_cache_key "$scheme$request_method$host$request_uri"; proxy_cache_valid 200 302 10m; proxy_cache_valid 404 1m; add_header X-Cache-Status $upstream_cache_status; } } # 静态文件缓存 location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ { expires 1y; add_header Cache-Control "public, immutable"; access_log off; } ``` ### 3. Gzip 压缩优化 ```nginx gzip on; gzip_vary on; gzip_proxied any; gzip_comp_level 6; gzip_min_length 1024; 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; ``` ## 安全配置 ### 1. 基础安全配置 ```nginx # 隐藏 Nginx 版本号 server_tokens off; # 防止点击劫持 add_header X-Frame-Options "SAMEORIGIN" always; # 防止 XSS 攻击 add_header X-XSS-Protection "1; mode=block" always; # 防止 MIME 类型嗅探 add_header X-Content-Type-Options "nosniff" always; # 内容安全策略(CSP) add_header Content-Security-Policy "default-src 'self'; script-src 'self' 'unsafe-inline';" always; # 限制请求方法 if ($request_method !~ ^(GET|HEAD|POST)$) { return 405; } ``` ### 2. 限制访问 ```nginx # 限制请求频率 limit_req_zone $binary_remote_addr zone=one:10m rate=1r/s; server { location /login { limit_req zone=one burst=5; # ... 其他配置 ... } } # 限制并发连接数 limit_conn_zone $binary_remote_addr zone=addr:10m; location /download { limit_conn addr 10; # 每个IP最多10个并发连接 } # 禁止特定IP访问 deny 192.168.1.1; allow 192.168.1.0/24; allow 10.0.0.0/8; deny all; ``` ### 3. 文件上传限制 ```nginx # 限制客户端请求体大小 client_max_body_size 10M; # 限制上传超时时间 client_body_timeout 60s; client_header_timeout 60s; ``` ## 监控和日志 ### 1. 自定义日志格式 ```nginx log_format detailed '$remote_addr - $remote_user [$time_local] ' '"$request" $status $body_bytes_sent ' '"$http_referer" "$http_user_agent" ' '$request_time $upstream_response_time ' '$upstream_addr $upstream_status'; # 按域名分开日志 access_log /var/log/nginx/example.com.access.log detailed; ``` ### 2. Nginx 状态页面 ```nginx # 启用状态模块(需编译时包含) location /nginx_status { stub_status on; access_log off; allow 127.0.0.1; deny all; } ``` 访问:`http://localhost/nginx_status` 显示: ``` Active connections: 1 server accepts handled requests 3 3 5 Reading: 0 Writing: 1 Waiting: 0 ``` ## 常用模块 ### 1. 查看已安装模块 ```bash nginx -V nginx -T # 显示完整配置 ``` ### 2. 安装额外模块 ```bash # 例如安装 GeoIP 模块 sudo apt install libnginx-mod-http-geoip # 重新加载配置 sudo systemctl reload nginx ``` ## 故障排查 ### 1. 常见问题解决 **问题1:配置文件错误** ```bash # 测试配置 sudo nginx -t # 查看错误日志 sudo tail -f /var/log/nginx/error.log # 查看特定站点错误 sudo tail -f /var/log/nginx/example.com.error.log ``` **问题2:权限问题** ```bash # 检查权限 sudo chown -R www-data:www-data /var/www/html sudo chmod -R 755 /var/www/html # 检查 SELinux/AppArmor sudo aa-status ``` **问题3:端口冲突** ```bash # 检查端口占用 sudo netstat -tlnp | grep :80 sudo ss -tlnp | grep :80 # 查看 Nginx 监听的端口 sudo nginx -T | grep listen ``` **问题4:性能问题** ```bash # 查看连接状态 ss -tan | grep :80 | wc -l # 查看 Nginx 进程状态 sudo systemctl status nginx top -p $(pgrep -d',' nginx) ``` ### 2. 调试模式 ```bash # 临时启用调试日志 sudo nginx -g 'error_log /var/log/nginx/error.log debug;' # 重新加载 sudo nginx -s reload ``` ## 维护脚本 ### 1. Nginx 配置备份 ```bash #!/bin/bash # /usr/local/bin/nginx-backup.sh BACKUP_DIR="/backup/nginx" DATE=$(date +%Y%m%d_%H%M%S) mkdir -p $BACKUP_DIR tar -czf $BACKUP_DIR/nginx_$DATE.tar.gz /etc/nginx /var/www/html # 保留最近7天的备份 find $BACKUP_DIR -name "*.tar.gz" -mtime +7 -delete ``` ### 2. 日志轮转 ```bash # Nginx 默认使用 logrotate sudo nano /etc/logrotate.d/nginx # 配置示例 /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 } ``` ## 卸载 Nginx ```bash # 停止服务 sudo systemctl stop nginx # 禁用服务 sudo systemctl disable nginx # 卸载 Nginx sudo apt purge nginx nginx-common # 删除配置文件和日志 sudo rm -rf /etc/nginx /var/log/nginx # 清理依赖包 sudo apt autoremove ```
请输入访问密码
开始访问