macOS and Linux nginx编译安装
1. 准备编译环境
首先安装必要的编译工具和依赖库:
Ubuntu/Debian:
bash
sudo apt-get update
sudo apt-get install build-essential libpcre3 libpcre3-dev zlib1g-devCentOS/RHEL:
bash
sudo yum install gcc-c++ pcre-devel zlib-develmacOS:
bash
brew install pcre2. 获取 Nginx 源码
bash
wget http://nginx.org/download/nginx-1.25.3.tar.gz # 替换为最新版本
tar zxvf nginx-1.25.3.tar.gz
cd nginx-1.25.33. 配置编译选项
运行配置脚本,常用选项包括:
bash
./configure \
--prefix=/usr/local/nginx \ # 安装目录
--user=nginx \ # 运行用户
--group=nginx \ # 运行组
--with-http_ssl_module \ # 启用SSL支持
--with-http_v2_module \ # 启用HTTP/2
--with-http_realip_module \ # 启用真实IP模块
--with-http_stub_status_module \ # 启用状态监控
--with-http_gzip_static_module \ # 启用gzip静态压缩
--with-pcre \ # PCRE正则支持
--with-stream \ # 启用TCP/UDP代理
--with-threads \ # 启用线程池
--with-debug # 调试模式(生产环境去掉)查看所有可用选项:
bash
./configure --help4. 编译和安装
bash
make install5. 创建系统用户和目录
bash
sudo useradd -r -s /sbin/nologin nginx
sudo mkdir -p /var/log/nginx
sudo chown -R nginx:nginx /var/log/nginx6. 创建systemd服务文件
/etc/systemd/system/nginx.service
text
[Unit]
Description=The NGINX HTTP and reverse proxy server
After=network.target
[Service]
Type=forking
User=nginx
Group=nginx
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=/usr/local/nginx/sbin/nginx -s quit
TimeoutStopSec=5
KillMode=mixed
[Install]
WantedBy=multi-user.target启用服务:
bash
sudo systemctl daemon-reload
sudo systemctl enable nginx
sudo systemctl start nginx7. 验证安装
bash
/usr/local/nginx/sbin/nginx -V输出应显示你配置的所有模块和选项。
8. 升级Nginx
bash
# 备份旧配置
cp -r /usr/local/nginx/conf /backup/nginx-conf
# 下载新版源码并编译
./configure [与之前相同的选项]
make
sudo make upgrade # 平滑升级(不中断服务)