Nginx 安装与配置指南
1. 更新包列表
首先,打开终端并更新系统的包列表:
sudo apt update
2. 安装 Nginx
使用以下命令安装 Nginx:
sudo apt install nginx
3. 启动 Nginx 服务
安装完成后,可以启动 Nginx 服务:
sudo systemctl start nginx
4. 设置 Nginx 开机自启动
如果希望在系统启动时自动启动 Nginx,可以使用以下命令:
sudo systemctl enable nginx
5. 检查 Nginx 状态
你可以使用以下命令检查 Nginx 服务的状态:
sudo systemctl status nginx
如果一切正常,你会看到 Nginx 正在运行。
6. 配置防火墙(可选)
如果你的服务器启用了防火墙(如 UFW),需要允许 HTTP 和 HTTPS 流量。运行以下命令:
sudo ufw allow 'Nginx Full'
7. 配置 Nginx 反向代理
创建配置文件 /etc/nginx/name.conf,内容如下:
server {
listen 80;
server_name api.chase-up.top;
location / {
proxy_pass http://127.0.0.1:3005; # 代理到后端3005端口
proxy_http_version 1.1; # 使用 HTTP/1.1
proxy_set_header Upgrade $http_upgrade; # 处理 WebSocket 连接
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host; # 保持主机头
proxy_set_header X-Real-IP $remote_addr; # 记录真实 IP
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; # 转发 IP
proxy_set_header X-Forwarded-Proto $scheme; # 转发协议
}
location ~* ^/api/ {
rewrite ^/api/(.*)$ /m1/6101316-5791982-default/api/$1 break;
proxy_pass https://m1.apifoxmock.com;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
# 其他优化设置
keepalive_timeout 65; # 设置 Keep-Alive 超时
proxy_read_timeout 90; # 设置读取超时
proxy_send_timeout 90; # 设置发送超时
# 日志配置(可选)
access_log /var/log/nginx/access.log; # 访问日志路径
error_log /var/log/nginx/error.log; # 错误日志路径
}
8. 重启 Nginx
应用配置更改后,重启 Nginx:
sudo systemctl restart nginx
9. 检查 Nginx 配置是否有误
在重启之前,建议检查配置文件是否有错误:
sudo nginx -t
10. 自动获取 SSL 证书
若要为域名启用 SSL,首先更新包列表并安装 Certbot:
sudo apt update
sudo apt install certbot python3-certbot-nginx
然后运行以下命令获取 SSL 证书:
sudo certbot --nginx -d api.chase-up.top