nginx指南

Nginx 操作手册 一、安装与启动 安装(Ubuntu) 1 sudo apt update 1 sudo apt install nginx -y 启动 / 停止 / 重启 1 sudo systemctl start nginx 1 sudo systemctl stop nginx 1 sudo systemctl restart nginx 1 sudo systemctl reload nginx 开机自启 1 sudo systemctl enable nginx 二、状态查看 查看运行状态 1 sudo systemctl status nginx 查看端口占用 1 lsof -i:80 1 ss -lntp | grep 80 三、配置文件结构 1 /etc/nginx/nginx.conf 1 /etc/nginx/conf.d/ 1 /etc/nginx/sites-enabled/ 1 /var/log/nginx/ 四、常用配置 基础 server 1 2 3 4 5 6 7 8 9 server { listen 80; server_name example.com; location / { root /usr/share/nginx/html; index index.html; } } 反向代理 1 2 3 location /api/ { proxy_pass http://127.0.0.1:8080; } 1 2 3 proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; 负载均衡 1 2 3 4 upstream backend { server 192.168.1.10:8080; server 192.168.1.11:8080; } 1 2 3 location / { proxy_pass http://backend; } HTTPS 1 2 3 4 5 6 7 8 9 10 11 server { listen 443 ssl; server_name example.com; ssl_certificate /etc/nginx/ssl/fullchain.pem; ssl_certificate_key /etc/nginx/ssl/privkey.pem; location / { root /usr/share/nginx/html; } } 1 2 3 4 5 server { listen 80; server_name example.com; return 301 https://$host$request_uri; } 五、配置测试 1 nginx -t 1 nginx -s reload 六、日志 1 /var/log/nginx/access.log 1 /var/log/nginx/error.log 1 tail -f /var/log/nginx/access.log 1 tail -f /var/log/nginx/error.log 七、性能优化 1 2 gzip on; gzip_types text/plain text/css application/json application/javascript; 1 2 worker_processes auto; worker_connections 10240; 八、常见排查 1 lsof -i:80 1 nginx -t 1 pkill -9 nginx 九、生产建议 1 user nginx; 1 client_max_body_size 20m; 1 server_tokens off; 1 autoindex off; 十、Docker 中运行 1 docker run -d --name nginx -p 80:80 nginx 1 docker run -d -p 80:80 -v /host/nginx.conf:/etc/nginx/nginx.conf nginx 1 docker logs nginx

January 2, 2026 · 2 min · 272 words