插件窝 干货文章 Nginx怎么编译安装

Nginx怎么编译安装

Nginx 安装 HTTP with 1050    来源:    2025-04-21

Nginx 编译安装指南

Nginx 是一个高性能的 HTTP 和反向代理服务器,以下是详细的编译安装步骤:

1. 安装依赖

在编译安装前,需要先安装必要的依赖库:

# 对于 CentOS/RHEL 系统
sudo yum install -y gcc gcc-c++ make pcre pcre-devel zlib zlib-devel openssl openssl-devel

# 对于 Ubuntu/Debian 系统
sudo apt-get update
sudo apt-get install -y build-essential libpcre3 libpcre3-dev zlib1g zlib1g-dev libssl-dev

2. 下载 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

3. 配置编译选项

./configure \
--prefix=/usr/local/nginx \
--user=nginx \
--group=nginx \
--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

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

4. 编译并安装

make
sudo make install

5. 创建系统用户

sudo useradd -r -s /sbin/nologin nginx

6. 创建服务管理脚本(Systemd)

创建 /usr/lib/systemd/system/nginx.service 文件:

[Unit]
Description=The nginx HTTP and reverse proxy server
After=network.target remote-fs.target nss-lookup.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=/bin/kill -s HUP $MAINPID
ExecStop=/bin/kill -s QUIT $MAINPID
PrivateTmp=true

[Install]
WantedBy=multi-user.target

然后执行:

sudo systemctl daemon-reload
sudo systemctl enable nginx
sudo systemctl start nginx

7. 验证安装

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

# 检查运行状态
sudo systemctl status nginx

# 测试访问
curl http://localhost

8. 配置环境变量(可选)

echo 'export PATH=$PATH:/usr/local/nginx/sbin' >> ~/.bashrc
source ~/.bashrc

常见问题解决

  1. 端口冲突:如果 80 端口被占用,可以修改 conf/nginx.conf 中的监听端口
  2. 权限问题:确保 Nginx 运行用户对相关目录有访问权限
  3. 模块缺失:如果需要额外模块,可以在配置时添加相应 --with- 选项

后续操作

  • 配置防火墙开放端口
  • 配置虚拟主机
  • 设置 HTTPS 证书
  • 优化 Nginx 配置参数

这样你就完成了 Nginx 的编译安装过程。编译安装可以让你更灵活地选择需要的模块和功能。