Nginx 是世界上最流行的 Web 服务器。学会 Nginx 的基本操作,你的 VPS 就能同时跑多个网站。
安装
apt install nginx -y
systemctl enable nginx --now
# 验证:访问 http://你的IP,应该看到 Nginx 欢迎页
虚拟主机:一台 VPS 跑 N 个网站
Nginx 根据请求的域名来判断该返回哪个网站的内容。
# 创建站点配置
nano /etc/nginx/sites-available/site1.com
# 内容:
server {
listen 80;
server_name site1.com www.site1.com;
root /var/www/site1;
index index.html index.php;
location / {
try_files $uri $uri/ =404;
}
}
# 启用站点
ln -s /etc/nginx/sites-available/site1.com /etc/nginx/sites-enabled/
nginx -t && systemctl reload nginx
同样的方式创建 site2.com 的配置,两个网站互不影响。
反向代理:把流量转到后端服务
你的 Node.js 应用跑在 localhost:3000,但用户需要访问 80/443 端口。用 Nginx 反向代理:
server {
listen 80;
server_name app.mydomain.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;
}
}
Let's Encrypt 免费 SSL
# 安装 certbot
apt install certbot python3-certbot-nginx -y
# 一键申请 SSL
certbot --nginx -d site1.com -d www.site1.com
# 自动续期(certbot 已自带定时器)
systemctl status certbot.timer
# 测试续期
certbot renew --dry-run
常用 Nginx 命令
nginx -t # 测试配置是否有语法错误
nginx -s reload # 平滑重载配置(不中断服务)
nginx -s stop # 立即停止
systemctl reload nginx
性能调优
# /etc/nginx/nginx.conf
worker_processes auto;
worker_connections 1024;
# 开启 gzip 压缩
gzip on;
gzip_types text/plain text/css application/json application/javascript text/xml;
gzip_min_length 1000;