Ubuntu 24.04 安装 Nginx 1.29.6 完整版教程
一、准备工作
在开始安装前,请确保系统已更新至最新状态并安装必要的依赖工具:
sudo apt update && sudo apt upgrade -y
sudo apt install -y build-essential libpcre3-dev libssl-dev zlib1g-dev wget
说明:上述命令安装了编译所需的基础工具(build-essential)、正则表达式库(libpcre3-dev)、SSL加密库(libssl-dev)、压缩库(zlib1g-dev)及下载工具(wget)。
重要路径
- 安装目录:/usr/local/nginx/
- 配置文件:/usr/local/nginx/conf/nginx.conf
- 网页目录:/usr/local/nginx/html/
- 日志目录:/usr/local/nginx/logs/
二、下载 Nginx 1.29.6 源码包
从 Nginx 官方网站下载最新的稳定版源码:
wget http://nginx.org/download/nginx-1.29.6.tar.gz
下载完成后解压源码包:
tar -zxvf nginx-1.29.6.tar.gz
cd nginx-1.29.6
- 配置编译参数(完整版功能)
cd /usr/local/src/nginx-1.29.6
执行以下命令配置 Nginx 功能模块,包含常用模块及完整功能支持:
./configure \
--prefix=/usr/local/nginx \
--user=nginx \
--group=nginx \
--with-http_ssl_module \
--with-http_v2_module \
--with-http_realip_module \
--with-http_addition_module \
--with-http_sub_module \
--with-http_dav_module \
--with-http_flv_module \
--with-http_mp4_module \
--with-http_gunzip_module \
--with-http_gzip_static_module \
--with-http_random_index_module \
--with-http_secure_link_module \
--with-http_stub_status_module \
--with-http_auth_request_module \
--with-threads \
--with-stream \
--with-stream_ssl_module \
--with-stream_realip_module
参数说明:
- --prefix:指定安装路径(推荐/usr/local/nginx)
- --user/--group:运行 Nginx 的用户及组(需提前创建)
- --with-http_ssl_module:启用 HTTPS 支持
- --with-stream:启用 TCP/UDP 代理功能
- 其他模块:支持 URL 重写、压缩、视频流、状态监控等完整功能
四、编译与安装
执行编译并安装 Nginx:
make -j$(nproc) # 多线程编译,提升速度
make install
创建 Nginx 用户及组(若未创建):
useradd -r -s /sbin/nologin nginx
创建全局命令
ln -s /usr/local/nginx/sbin/nginx /usr/local/bin/nginx
五、配置系统服务
创建 systemd 服务文件以实现开机自启:
vi /etc/systemd/system/nginx.service
粘贴以下内容:
Unit
Description=Nginx HTTP Server
After=network.target
Service
Type=forking
PIDFile=/usr/local/nginx/logs/nginx.pid
ExecStart=/usr/local/nginx/sbin/nginx
ExecReload=/usr/local/nginx/sbin/nginx -s reload
ExecStop=/usr/local/nginx/sbin/nginx -s stop
PrivateTmp=true
Install
WantedBy=multi-user.target
保存并退出后,重载 systemd 配置:
systemctl daemon-reload
systemctl enable --now nginx # 启用并启动服务
六、验证安装结果
检查 Nginx 版本及模块:
/usr/local/nginx/sbin/nginx -V
输出应包含nginx version: nginx/1.29.6及已配置的模块列表。
通过浏览器访问服务器 IP,若显示 "Welcome to nginx!" 页面,说明安装成功。
七、常用命令
- 启动服务:sudo systemctl start nginx
- 停止服务:sudo systemctl stop nginx
- 重启服务:sudo systemctl restart nginx
- 重新加载配置:sudo systemctl reload nginx
- 查看状态:sudo systemctl status nginx
防火墙放行 80/443
ufw allow 80/tcp
ufw allow 443/tcp
验证:
curl http://localhost
八、注意事项
- 防火墙配置:若启用 UFW,需允许 HTTP(80)和 HTTPS(443)端口:
sudo ufw allow 'Nginx Full' - 配置文件路径:主配置文件位于/usr/local/nginx/conf/nginx.conf
- 日志文件路径:访问日志和错误日志位于/usr/local/nginx/logs/
- 升级方法:如需升级版本,需重新下载源码并重复编译安装步骤