Ubuntu版本:Ubuntu 24.04.2 LTS
一、安装Nginx
更新系统软件包
安装前需确保系统处于最新状态,避免依赖冲突sudo apt update && sudo apt upgrade -y
安装Nginx主程序
Ubuntu官方仓库已包含稳定版Nginx,直接安装即可sudo apt install nginx -y
验证安装与启动服务
sudo systemctl start nginx # 启动服务 sudo systemctl enable nginx # 设置开机自启 sudo systemctl status nginx # 检查运行状态
访问
http://服务器IP
,若显示Nginx欢迎页即安装成功
二、配置反向代理
创建专用配置文件
建议在/etc/nginx/sites-available/
目录下新建独立配置文件sudo nano /etc/nginx/sites-available/reverse-proxy.conf
编写反向代理规则
添加以下内容(以代理本地8080端口的服务为例):nginx
server { listen 80; server_name your-domain.com; # 替换为域名或IP location / { proxy_pass http://localhost: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; } }
关键参数说明:
proxy_pass
:后端服务的实际地址(支持IP:端口或域名)proxy_set_header
:传递客户端真实信息给后端
启用配置并测试
sudo ln -s /etc/nginx/sites-available/reverse-proxy.conf /etc/nginx/sites-enabled/ sudo nginx -t # 检查语法 sudo systemctl reload nginx # 热重载配置
三、高级配置(可选)
负载均衡
若需代理多个后端服务器,使用upstream
模块upstream backend { server 192.168.1.10:8080 weight=3; # 权重分配 server 192.168.1.11:8080; least_conn; # 最小连接策略 } server { location / { proxy_pass http://backend; # 指向upstream组 } }
HTTPS加密
通过Let's Encrypt获取免费SSL证书sudo apt install certbot python3-certbot-nginx sudo certbot --nginx -d your-domain.com
自动更新证书的定时任务会同步创建。
性能优化
在nginx.conf
中调整全局参数http { gzip on; # 启用压缩 proxy_buffers 8 16k; # 缓冲区优化 proxy_connect_timeout 60s; }
四、故障排查
- 日志分析:
tail -f /var/log/nginx/error.log # 实时查看错误日志
- 端口占用检查:
sudo lsof -i :80 # 排查端口冲突[6](@ref)