nginx 基本使用和高级用法详解
一、nginx 简介
nginx 是一个高性能的 http 和反向代理服务器,具有占用内存少、并发能力强等特点,广泛应用于 web 服务、负载均衡、静态资源处理和反向代理等场景。
二、基本安装与使用
1. 安装 nginx
ubuntu/debian
sudo apt update sudo apt install nginx
centos/rhel
sudo yum install nginx # 或 sudo dnf install nginx
2. 基本操作命令
# 启动 sudo systemctl start nginx # 停止 sudo systemctl stop nginx # 重启 sudo systemctl restart nginx # 重新加载配置(不中断服务) sudo systemctl reload nginx # 查看状态 sudo systemctl status nginx # 开机自启 sudo systemctl enable nginx
三、配置文件结构
1. 主要配置文件目录结构
/etc/nginx/ ├── nginx.conf # 主配置文件 ├── conf.d/ # 额外配置文件目录 ├── sites-available/ # 可用站点配置文件 └── sites-enabled/ # 已启用站点配置文件(软链接指向 sites-available)
2. 基本配置示例(/etc/nginx/nginx.conf)
user nginx; worker_processes auto; error_log /var/log/nginx/error.log; pid /run/nginx.pid; events { worker_connections 1024; use epoll; multi_accept on; } 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; sendfile on; tcp_nopush on; tcp_nodelay on; keepalive_timeout 65; types_hash_max_size 2048; include /etc/nginx/conf.d/*.conf; include /etc/nginx/sites-enabled/*; }
四、虚拟主机配置
1. 基本虚拟主机配置
# /etc/nginx/sites-available/example.com server { listen 80; server_name example.com www.example.com; root /var/www/example.com; index index.html index.htm; location / { try_files $uri $uri/ =404; } # 静态资源缓存优化 location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ { expires 1y; add_header cache-control "public, immutable"; } }
2. 启用站点
# 创建软链接启用站点 sudo ln -s /etc/nginx/sites-available/example.com /etc/nginx/sites-enabled/ # 测试配置是否正确 sudo nginx -t # 重新加载配置 sudo systemctl reload nginx
五、高级配置技巧
1. 反向代理配置
server { listen 80; server_name api.example.com; location / { proxy_pass http://localhost:3000; 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 30s; proxy_send_timeout 30s; proxy_read_timeout 30s; # 缓冲设置 proxy_buffering on; proxy_buffer_size 4k; proxy_buffers 8 4k; } }
2. 负载均衡
upstream backend { server backend1.example.com weight=3; server backend2.example.com; server backend3.example.com; server backup.example.com backup; } server { listen 80; server_name app.example.com; location / { proxy_pass http://backend; proxy_set_header host $host; proxy_set_header x-real-ip $remote_addr; } }
3. ssl/tls 配置
server { listen 443 ssl http2; server_name example.com; 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-aes128-gcm-sha256:ecdhe-rsa-aes256-gcm-sha384; ssl_prefer_server_ciphers off; # hsts 强制 https add_header strict-transport-security "max-age=63072000" always; root /var/www/example.com; index index.html; }
4. 缓存配置
代理缓存
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_pass http://backend; proxy_cache_valid 200 302 10m; proxy_cache_valid 404 1m; add_header x-cache-status $upstream_cache_status; } }
静态资源缓存
location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg)$ { expires 1y; add_header cache-control "public, immutable"; }
5. 安全配置
# 隐藏版本号 server_tokens off; # 安全响应头 add_header x-frame-options "sameorigin" always; add_header x-xss-protection "1; mode=block" always; add_header x-content-type-options "nosniff" always; add_header referrer-policy "no-referrer-when-downgrade" always; add_header content-security-policy "default-src 'self' http: https: data: blob: 'unsafe-inline'" always; # 上传大小限制 client_max_body_size 10m; # 限制非法请求方法 if ($request_method !~ ^(get|post|head)$) { return 405; }
6. 限流配置
# 定义限流区域 limit_req_zone $binary_remote_addr zone=api:10m rate=10r/s; limit_req_zone $binary_remote_addr zone=login:10m rate=2r/m; server { location /api/ { limit_req zone=api burst=20 nodelay; proxy_pass http://backend; } location /login { limit_req zone=login burst=5; proxy_pass http://backend; } }
7. url 重写和重定向
server { # 强制跳转 https if ($scheme = http) { return 301 https://$server_name$request_uri; } # 路径重定向 location /old-path { return 301 /new-path; } # 去除 .html 扩展名 location / { try_files $uri $uri.html $uri/ =404; } # restful url 重写 location /api/v1/users { rewrite ^/api/v1/users/(.*)$ /api/v1/users?id=$1 last; } }
8. 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;
六、性能优化配置
1. 连接优化
events { worker_connections 4096; use epoll; multi_accept on; } http { sendfile on; tcp_nopush on; tcp_nodelay on; keepalive_timeout 65; keepalive_requests 1000; # 文件描述符缓存 open_file_cache max=200000 inactive=20s; open_file_cache_valid 30s; open_file_cache_min_uses 2; open_file_cache_errors on; }
2. 工作进程优化
worker_processes auto; worker_cpu_affinity auto; # 提高文件描述符限制 worker_rlimit_nofile 65535;
七、日志配置
1. 自定义日志格式
log_format main '$remote_addr - $remote_user [$time_local] "$request" ' '$status $body_bytes_sent "$http_referer" ' '"$http_user_agent" "$http_x_forwarded_for" ' 'rt=$request_time uct="$upstream_connect_time" ' 'uht="$upstream_header_time" urt="$upstream_response_time"'; access_log /var/log/nginx/access.log main; error_log /var/log/nginx/error.log warn;
2. 日志分割脚本(rotate_nginx_logs.sh)
#!/bin/bash # rotate_nginx_logs.sh log_dir="/var/log/nginx" date=$(date -d "yesterday" +%y-%m-%d) mv $log_dir/access.log $log_dir/access.$date.log mv $log_dir/error.log $log_dir/error.$date.log # 通知 nginx 重新打开日志文件 kill -usr1 $(cat /var/run/nginx.pid) # 压缩7天前的日志 find $log_dir -name "*.log" -mtime +7 -exec gzip {} \;
提示:可配合
cron
定时执行日志轮转。
八、监控和调试
1. 状态页面配置
server { listen 8080; server_name localhost; location /nginx_status { stub_status on; access_log off; allow 127.0.0.1; deny all; } }
访问 http://localhost:8080/nginx_status
可查看连接状态。
2. 调试常用命令
# 测试配置语法 sudo nginx -t # 打印完整配置(含 include) sudo nginx -t # 查看 nginx 编译参数和模块 nginx -v # 实时查看日志 tail -f /var/log/nginx/access.log tail -f /var/log/nginx/error.log # 压力测试(apache bench) ab -n 1000 -c 100 http://example.com/
九、docker 中的 nginx
1. dockerfile 示例
from nginx:alpine copy nginx.conf /etc/nginx/nginx.conf copy sites/ /etc/nginx/sites-available/ copy html/ /usr/share/nginx/html/ run ln -s /etc/nginx/sites-available/example.com /etc/nginx/sites-enabled/ expose 80 443 cmd ["nginx", "-g", "daemon off;"]
2. docker compose 示例
version: '3.8' services: nginx: image: nginx:alpine ports: - "80:80" - "443:443" volumes: - ./nginx.conf:/etc/nginx/nginx.conf - ./sites:/etc/nginx/sites-available - ./html:/usr/share/nginx/html - ./ssl:/etc/ssl networks: - webnet networks: webnet: driver: bridge
结语
本指南涵盖了 nginx 的 基础安装、虚拟主机、反向代理、负载均衡、ssl 配置、缓存、安全加固、限流、url 重写、gzip 压缩、性能调优、日志管理、监控调试 以及 docker 部署 等核心内容,适用于构建高可用、高性能、安全的 web 服务架构。
建议在生产环境中结合具体业务场景进行配置优化,并定期审查安全策略和性能指标。
到此这篇关于nginx 基本使用和高级用法详解的文章就介绍到这了,更多相关nginx 安装使用内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论