> 你有一台 VPS,想同时跑博客、网盘、监控面板,但只有一个 80 端口,怎么办?Nginx 反向代理就是标准答案。它就像一个前台,把不同域名的请求分发到不同的后台服务。
---
## 反向代理是什么?
举个生活例子:你去公司找张三,前台接待员帮你联系张三,然后带你去会议室。你不需要知道张三在哪个工位。Nginx 就是这个前台。
---
## 安装 Nginx
```bash
apt update && apt install nginx -y
systemctl start nginx
systemctl enable nginx
```
访问服务器 IP,看到 Nginx 欢迎页就成功了。
---
## 基础配置文件结构
Nginx 配置文件在 /etc/nginx/ 目录下:
- nginx.conf:主配置文件
- sites-available/:存放所有站点配置
- sites-enabled/:已启用的站点(软链接到 sites-available)
---
## 配置第一个反向代理
假设博客运行在本地 8080 端口,想通过 blog.example.com 访问:
```nginx
server {
listen 80;
server_name blog.example.com;
location / {
proxy_pass http://127.0.0.1:8080;
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;
}
}
```
创建文件后启用:
```bash
ln -s /etc/nginx/sites-available/blog /etc/nginx/sites-enabled/
nginx -t # 检查配置语法
systemctl reload nginx
```
---
## 一台服务器跑多个网站
| 网站 | 域名 | 后端端口 |
|------|------|---------|
| 博客 | blog.example.com | 8080 |
| 网盘 | cloud.example.com | 8081 |
| 监控 | status.example.com | 3000 |
只需要在 Nginx 中为每个域名创建独立的 server 块,各自 proxy_pass 到对应端口即可。
---
## 配置 SSL(HTTPS)
```bash
apt install certbot python3-certbot-nginx -y
certbot --nginx -d blog.example.com
```
Certbot 会自动修改 Nginx 配置加上 SSL 支持,证书到期前也会自动续期。
---
## 常用优化配置
```nginx
client_max_body_size 100m; # 文件上传大小限制
gzip on;
gzip_types text/plain text/css application/json application/javascript;
location ~* \.(jpg|png|gif|css|js|ico)$ {
expires 30d;
add_header Cache-Control "public, immutable";
}
```
---
配置好 Nginx 反向代理,一台 1 核 1G 的小 VPS 跑 5 到 10 个小网站完全没压力。这是每个站长必备的技能。