插件窝 干货文章 在lnmp环境中的nginx怎么编译安装

在lnmp环境中的nginx怎么编译安装

Nginx module local 安装 351    来源:    2025-04-22

LNMP环境中Nginx的编译安装指南

准备工作

在开始编译安装Nginx前,请确保系统已安装必要的编译工具和依赖库:

# CentOS/RHEL系统
yum install -y gcc gcc-c++ make autoconf automake pcre pcre-devel zlib zlib-devel openssl openssl-devel

# Ubuntu/Debian系统
apt-get install -y build-essential autoconf automake libtool pkg-config libpcre3-dev zlib1g-dev libssl-dev

下载Nginx源码

# 创建安装目录
mkdir -p /usr/local/src/nginx
cd /usr/local/src/nginx

# 下载最新稳定版Nginx (请替换为最新版本号)
wget http://nginx.org/download/nginx-1.25.3.tar.gz
tar zxvf nginx-1.25.3.tar.gz
cd nginx-1.25.3

配置编译选项

./configure \
--prefix=/usr/local/nginx \
--user=www \
--group=www \
--with-http_ssl_module \
--with-http_v2_module \
--with-http_realip_module \
--with-http_stub_status_module \
--with-http_gzip_static_module \
--with-pcre \
--with-stream \
--with-stream_ssl_module \
--with-threads

常用配置选项说明: - --prefix:指定安装目录 - --user/--group:指定运行用户和组 - --with-http_ssl_module:启用HTTPS支持 - --with-http_v2_module:启用HTTP/2支持 - --with-http_stub_status_module:启用状态监控页面

编译和安装

# 编译
make

# 安装
make install

创建系统服务

创建systemd服务文件/lib/systemd/system/nginx.service

[Unit]
Description=The NGINX HTTP and reverse proxy server
After=syslog.target network-online.target remote-fs.target nss-lookup.target
Wants=network-online.target

[Service]
Type=forking
PIDFile=/usr/local/nginx/logs/nginx.pid
ExecStartPre=/usr/local/nginx/sbin/nginx -t
ExecStart=/usr/local/nginx/sbin/nginx
ExecReload=/usr/local/nginx/sbin/nginx -s reload
ExecStop=/bin/kill -s QUIT $MAINPID
PrivateTmp=true

[Install]
WantedBy=multi-user.target

启用并启动Nginx服务:

systemctl enable nginx
systemctl start nginx

验证安装

# 检查版本
/usr/local/nginx/sbin/nginx -v

# 检查运行状态
systemctl status nginx

# 测试配置文件
/usr/local/nginx/sbin/nginx -t

环境变量配置

为了方便使用,可以将Nginx添加到PATH中:

echo 'export PATH=/usr/local/nginx/sbin:$PATH' >> /etc/profile
source /etc/profile

可选配置

  1. 添加第三方模块: 在configure时使用--add-module=/path/to/module添加第三方模块

  2. 性能调优

    • 调整worker_processes为CPU核心数
    • 配置worker_connections
  3. 日志轮转: 配置logrotate来管理Nginx日志

常见问题解决

  1. 端口冲突

    netstat -tunlp | grep 80
    

    停止占用80端口的服务或修改Nginx监听端口

  2. 权限问题

    chown -R www:www /usr/local/nginx
    
  3. 依赖缺失: 根据编译错误提示安装缺少的依赖库

  4. 启动失败: 检查错误日志/usr/local/nginx/logs/error.log

通过以上步骤,您应该已经成功在LNMP环境中编译安装了Nginx。