1. 安装所有编译依赖(一次性装全,避免报错)
bash
yum install -y gcc gcc-c++ make wget pcre-devel zlib-devel openssl-devel
2. 下载最新稳定版 Nginx 源码(1.26.0 是当前最新稳定版)
bash
cd /tmp && wget http://nginx.org/download/nginx-1.26.0.tar.gz -O nginx.tar.gz
3. 解压源码包
bash
tar zxf nginx.tar.gz && cd nginx-1.26.0
4. 配置编译参数(启用 SSL,安装到 /usr/local/nginx)
bash
./configure --prefix=/usr/local/nginx --with-http_ssl_module
5. 编译并安装(-j 后跟CPU核心数,加速编译,nproc自动识别)
bash
make -j $(nproc) && make install
6. 创建系统服务(让 Nginx 能被 systemctl 管理)
bash
cat > /usr/lib/systemd/system/nginx.service << 'EOF'
[Unit]
Description=Nginx High Performance Web Server
After=network.target remote-fs.target nss-lookup.target
[Service]
Type=forking
PIDFile=/usr/local/nginx/logs/nginx.pid
ExecStart=/usr/local/nginx/sbin/nginx -c /usr/local/nginx/conf/nginx.conf
ExecReload=/usr/local/nginx/sbin/nginx -s reload
ExecStop=/usr/local/nginx/sbin/nginx -s stop
PrivateTmp=true
Restart=on-failure
[Install]
WantedBy=multi-user.target
EOF
7. 重新加载系统服务配置,启动 Nginx 并设置开机自启
bash
systemctl daemon-reload
systemctl start nginx
systemctl enable nginx
8. 验证安装结果
echo "Nginx 版本:"
bash
/usr/local/nginx/sbin/nginx -v
echo -e "\nNginx 服务状态:"
bash
systemctl status nginx --no-pager
安装后验证访问
本地测试:执行 curl http://127.0.0.1,能返回 Nginx 欢迎页的 HTML 代码,说明服务正常;
公网测试:
登录阿里云轻量应用服务器控制台 → 找到你的实例 → 点击「防火墙」;
添加规则:协议选 TCP,端口填 80,来源填 0.0.0.0/0,保存;
打开浏览器,输入服务器公网 IP(如 http://120.xx.xx.xx),能看到 Nginx 默认欢迎页即为全部成功。
后续常用命令(编译安装版)
bash
运行
启动
systemctl start nginx
停止
systemctl stop nginx
重启
systemctl restart nginx
重新加载配置(不中断服务)
systemctl reload nginx
查看状态
systemctl status nginx
查看 Nginx 配置是否有语法错误
/usr/local/nginx/sbin/nginx -t
修改nginx配置(若依前后分离版本,服务器配置-标准配置)
bash
vi /usr/local/nginx/conf/nginx.conf
bash
location / {
root /home/dist;
try_files $uri $uri/ /index.html;
index index.html index.htm;
}
location /prod-api/ {
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Credentials' 'true';
add_header 'Access-Control-Allow-Methods' 'OPTIONS, GET, POST';
proxy_pass http://localhost:8080/;
proxy_connect_timeout 300s;
proxy_send_timeout 300s;
proxy_read_timeout 300s;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
bash
systemctl reload nginx