一、Nginx 简介
Nginx 是一款高性能的 HTTP 和反向代理服务器,具备高并发、低资源消耗等优点,广泛应用于 Web 服务器领域。
二、安装 Nginx
1. 在 CentOS 上安装
- 更新软件包:
sudo yum update
- 安装 EPEL 仓库:
sudo yum install epel-release
- 安装 Nginx:
sudo yum install nginx
- 启动 Nginx:
sudo systemctl start nginx
- 设置开机自启:
sudo systemctl enable nginx
2. 在 Ubuntu 上安装
- 更新软件包:
sudo apt update
- 安装 Nginx:
sudo apt install nginx
- 启动 Nginx:
sudo systemctl start nginx
- 设置开机自启:
sudo systemctl enable nginx
三、配置 Nginx 反向代理
- 进入配置目录:
/etc/nginx/conf.d/
- 创建反向代理配置文件:
sudo vi proxy.conf
- 添加以下内容:
nginx
server {
listen 80;
server_name your_domain.com;
location / {
proxy_pass http://backend_server_ip:backend_server_port;
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 Connection keep-alive;
}}
- 保存并退出。
- 检查配置文件语法是否正确:
sudo nginx -t
- 重启 Nginx 使配置生效:
sudo systemctl restart nginx
四、配置 HTTPS(可选)
- 安装 Certbot:
sudo apt install certbot python3-certbot-nginx
sudo yum install -y https://dl.eff.org/certbot/centos/certbot-33.2.1-1.el7.ng.noarch.rpm
- 在 CentOS 上:
- 在 Ubuntu 上:
- 获取 SSL 证书:
sudo certbot --nginx -d your_domain.com
- 按照提示操作,完成证书安装。
- 设置自动更新证书:
sudo certbot renew --dry-run
五、防火墙设置
- 开放 Nginx 端口:
sudo ufw allow 'Nginx Full'
sudo ufw reload
sudo firewall-cmd --permanent --add-service=http
sudo firewall-cmd --permanent --add-service=https
sudo firewall-cmd --reload
- 在 CentOS 上:
- 在 Ubuntu 上:
六、验证反向代理是否成功
- 在浏览器中访问
http://your_domain.com
,如果能正常访问后端服务器的内容,则说明反向代理配置成功。
七、注意事项
- 定期检查 Nginx 配置文件的正确性,确保反向代理功能正常运行。
- 定期更新 SSL 证书,避免证书过期导致 HTTPS 访问出现问题。
- 根据实际需求调整 Nginx 的性能参数,以获得最佳的性能表现。
八、知识拓展
- Nginx 负载均衡:Nginx 可以作为负载均衡器,将客户端请求分发到多个后端服务器上,提高系统的可用性和性能。
- Nginx 缓存:Nginx 支持缓存功能,可以缓存后端服务器的响应内容,减少后端服务器的负载,提高响应速度。
- Nginx 访问控制:Nginx 可以通过配置访问控制规则,限制特定 IP 地址或用户对网站的访问,提高网站的安全性。