以编译的方式安装NGINX(Debian)

某家机子跑路了,之前用lnmp脚本部署的网站都得重新来,鉴于前几年lnmp的投毒事件,这次决定手动编译安装Nginx。

安装前置依赖

1
apt install  build-essential libpcre3 libpcre3-dev libssl-dev

我那台机子的话只安装这些依赖就够了,具体缺什么依赖之后在设置./counfigure时会有报错的,照着安装就是

配置Nginx系统用户

考虑到安全因素,我们有必要设置一个用户来运行Nginx,限制进程权限

1
2
3
adduser --system --no-create-home --group www  # Debian
#或者adduser --system --group www
#区别是下面这个会创建/home/www,以后放网站文件也是好的,当然完全可以先不创建,用到了在mkdir

下载Nginx并解压进入文件夹

1
2
wget https://nginx.org/download/nginx-1.26.3.tar.gz #链接自行替换为想要的版本,可以去nginx.org/download中找
tar -zxvf nginx-1.26.3.tar.gz && cd nginx-1.26.3

编译参数配置并编译

通过./configure进行配置,示例如下:

1
2
3
4
5
6
7
8
9
10
11
12
./configure \
--user=www \
--group=www \
--with-http_ssl_module \
--with-http_gzip_static_module \
--with-http_stub_status_module \
--with-http_v2_module \
--with-http_v3_module \
--with-http_realip_module \
--with-stream \
--with-stream_ssl_module \
--with-stream_ssl_preread_module \

以上是我用的配置,用户名与之前创建的新用户一致,模块可以参考Nginx官网文档,根据自己需要添加。

./configure完成后就可以编译了

1
make && make install

不出意外的话编译完成后的Nginx就在’/usr/local/nginx/sbin/nginx’了,可以用’/usr/local/nginx/sbin/nginx -V’试一试。

添加PATH

1
nano /etc/profile

在文件末尾添加:

1
export PATH=$PATH:/usr/local/nginx/sbin #仅适合本教程,请根据实际路径修改

保存后执行

1
source /etc/profile

即成功添加到PATH且永久有效

验证

1
nginx -v #应输出版本号

添加到systemd并允许开机自启

配置service

在 /etc/systemd/system/ 目录下新建 nginx.service 文件:

1
vim /etc/systemd/system/nginx.service

内容如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
[Unit]
Description=The NGINX HTTP and reverse proxy server
After=network.target

[Service]
Type=forking
PIDFile=/usr/local/nginx/logs/nginx.pid # 编译安装的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
PrivateTmp=true

[Install]
WantedBy=multi-user.target

设置并启用服务

1
2
3
4
5
6
7
8
# 重新加载 systemd 配置
sudo systemctl daemon-reload

# 启动 Nginx 服务
sudo systemctl start nginx

# 设置开机自启
sudo systemctl enable nginx

以编译的方式安装NGINX(Debian)
https://nekonya.one/2025/04/09/以编译的方式安装NGINX(Debian)/
作者
Guawazi233
发布于
2025年4月9日
许可协议