Nginx 备忘单
常用命令
- nginx - 启动Nginx服务
- nginx -s stop - 快速停止Nginx服务
- nginx -s quit - 优雅停止Nginx服务
- nginx -s reload - 重新加载配置文件
- nginx -t - 测试配置文件是否正确
- nginx -v - 显示Nginx版本
- nginx -V - 显示Nginx版本及配置参数
配置文件位置
- 主配置文件: /etc/nginx/nginx.conf
- 站点配置文件: /etc/nginx/sites-available/
- 启用的站点: /etc/nginx/sites-enabled/ (通常为链接)
- 默认文档根目录: /var/www/html
- 日志文件: /var/log/nginx/access.log 和 /var/log/nginx/error.log
基本站点配置
server {
listen 80;
server_name example.com www.example.com;
root /var/www/example.com;
index index.html index.htm index.php;
access_log /var/log/nginx/example_access.log;
error_log /var/log/nginx/example_error.log;
location / {
try_files $uri $uri/ =404;
}
}
反向代理配置
# 将请求代理到本地3000端口的应用
server {
listen 80;
server_name api.example.com;
location / {
proxy_pass http://localhost:3000;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
}
}
HTTPS配置
server {
listen 443 ssl;
server_name example.com www.example.com;
ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
# SSL配置
ssl_protocols TLSv1.2 TLSv1.3;
ssl_prefer_server_ciphers on;
ssl_ciphers 'ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384';
root /var/www/example.com;
index index.html;
location / {
try_files $uri $uri/ =404;
}
}
# HTTP重定向到HTTPS
server {
listen 80;
server_name example.com www.example.com;
return 301 https://$host$request_uri;
}