Nginx 是一个高性能的 HTTP 和反向代理服务器,以下是详细的编译安装步骤:
在编译安装前,需要先安装必要的依赖库:
# 对于 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
# 下载最新稳定版(请替换为最新版本号)
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=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
:启用状态监控页面
make
sudo make install
sudo useradd -r -s /sbin/nologin nginx
创建 /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
# 检查版本
/usr/local/nginx/sbin/nginx -v
# 检查运行状态
sudo systemctl status nginx
# 测试访问
curl http://localhost
echo 'export PATH=$PATH:/usr/local/nginx/sbin' >> ~/.bashrc
source ~/.bashrc
conf/nginx.conf
中的监听端口--with-
选项这样你就完成了 Nginx 的编译安装过程。编译安装可以让你更灵活地选择需要的模块和功能。