Ubuntu Nginx 编译安装教程
本文将指导您在 Ubuntu 系统上通过编译安装 Nginx,以获得更灵活的配置和性能优化。编译安装可自定义 Nginx 功能模块,避免默认安装包的局限性。
准备工作
- 确保 Ubuntu 20.04/22.04 系统
- 系统预装编译依赖:gcc, make, pcre, zlib, openssl
- 使用 sudo 权限执行
安装编译依赖
- 更新软件包列表
- 安装编译工具链
- 验证安装
sudo apt update
sudo apt install build-essential libpcre2-dev libssl-dev zlib1g-dev
gcc --version
下载 Nginx 源码
- 获取最新稳定版
- 解压源码
wget https://nginx.org/download/nginx-1.25.3.tar.gz
tar -zxvf nginx-1.25.3.tar.gz
配置编译选项
进入解压目录执行 ./configure 命令,以下为常用模块配置示例:
./configure \
--prefix=/usr/local/nginx \
--sbin-path=/usr/local/nginx/sbin/nginx \
--conf-path=/usr/local/nginx/nginx.conf \
--pid-path=/usr/local/nginx/logs/nginx.pid \
--with-http_v2_module \
--with-http_ssl_module \
--with-http_realip_module \
--with-http_stub_status_module \
--with-http_gzip_static_module \
--with-pcre=../pcre-8.45 \
--with-zlib=../zlib-1.2.11 \
--with-openssl=../openssl-1.1.1l
关键参数说明:
- –with-http_ssl_module:启用 HTTPS 支持
- –with-http_stub_status_module:提供状态监控接口
- –with-http_gzip_static_module:静态文件 Gzip 压缩
编译与安装
- 执行编译
- 安装程序
make
sudo make install
启动与测试
- 启动 Nginx
- 检查状态
- 访问测试页
sudo /usr/local/nginx/sbin/nginx
sudo /usr/local/nginx/sbin/nginx -t
curl http://127.0.0.1
注意事项与技巧
- 编译时若出现 make: *** [objects] Error 1,检查依赖是否完整
- 使用 –with-http_sub_module 可扩展功能
- 建议将 Nginx 添加到 systemd 服务管理
卸载方法
sudo make uninstall