一、准备工作
1. 安装编译依赖
sudo apt update
sudo apt install -y \
build-essential \
libpcre3-dev \
zlib1g-dev \
libssl-dev \
libxml2-dev \
libxslt1-dev \
libgd-dev \
libperl-dev
✅ 这些库用于支持:
pcre:正则表达式(rewrite 必需)zlib:gzip 压缩openssl:HTTPS/SSL 支持- 其他:可选模块(如 image filter、perl 模块等)
2. 创建 nginx 用户(非 root 运行,更安全)
sudo useradd -r -s /sbin/nologin -d /var/cache/nginx nginx
-r:系统用户;-s /sbin/nologin:禁止登录;-d:指定 home 目录(日志/缓存用)
二、下载并解压 Nginx 源码
# 进入临时目录
cd /tmp
# 下载最新稳定版(请到 https://nginx.org/en/download.html 查看最新版本)
NGINX_VERSION=1.26.1
wget https://nginx.org/download/nginx-${NGINX_VERSION}.tar.gz
# 解压
tar -zxvf nginx-${NGINX_VERSION}.tar.gz
cd nginx-${NGINX_VERSION}
三、配置编译选项(关键步骤)
运行 ./configure 设置安装路径和模块:
./configure \
--prefix=/usr/local/nginx \
--sbin-path=/usr/sbin/nginx \
--conf-path=/etc/nginx/nginx.conf \
--error-log-path=/var/log/nginx/error.log \
--http-log-path=/var/log/nginx/access.log \
--pid-path=/run/nginx.pid \
--lock-path=/run/nginx.lock \
--user=nginx \
--group=nginx \
--with-http_ssl_module \
--with-http_v2_module \
--with-http_realip_module \
--with-http_gzip_static_module \
--with-http_stub_status_module \
--with-http_sub_module \
--with-http_secure_link_module \
--with-pcre \
--with-file-aio \
--with-threads \
--with-stream \
--with-stream_ssl_module \
--with-stream_realip_module
🔍 参数说明:
| 参数 | 作用 |
|---|---|
--prefix | 安装根目录 |
--sbin-path | nginx 命令路径(方便直接执行) |
--conf-path | 主配置文件路径 |
--user/--group | 工作进程运行用户 |
--with-http_ssl_module | 启用 HTTPS(必需) |
--with-http_v2_module | 支持 HTTP/2 |
--with-http_stub_status_module | 开启状态页(/nginx_status) |
--with-stream | 四层 TCP/UDP 负载均衡 |
--with-pcre | 使用系统 PCRE 库(用于 rewrite) |
💡 如需添加第三方模块(如
ngx_cache_purge),在此处加--add-module=/path/to/module
四、编译并安装
# 编译(多核加速)
make -j$(nproc)
# 安装(复制文件到指定目录)
sudo make install
⏱️ 编译时间:通常 1~5 分钟,取决于服务器性能。
五、验证安装
# 检查版本和模块
nginx -V
# 测试配置文件语法
sudo nginx -t
# 输出应类似:
# nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
# nginx: configuration file /etc/nginx/nginx.conf test is successful
六、配置 systemd 服务(开机自启)
创建服务文件:
sudo tee /etc/systemd/system/nginx.service <<'EOF'
[Unit]
Description=The NGINX HTTP and reverse proxy server
After=network.target remote-fs.target nss-lookup.target
[Service]
Type=forking
PIDFile=/run/nginx.pid
ExecStartPre=/usr/sbin/nginx -t
ExecStart=/usr/sbin/nginx
ExecReload=/bin/kill -s HUP $MAINPID
KillSignal=SIGQUIT
TimeoutStopSec=5
KillMode=process
PrivateTmp=true
[Install]
WantedBy=multi-user.target
EOF
重载 systemd 并启动:
sudo systemctl daemon-reload
sudo systemctl start nginx
sudo systemctl enable nginx
sudo systemctl status nginx
七、防火墙放行(如启用)
sudo ufw allow 'Nginx Full'
八、常用目录确认
| 用途 | 路径 |
|---|---|
| 主配置文件 | /etc/nginx/nginx.conf |
| 站点配置目录 | /etc/nginx/conf.d/(需在主配置中 include) |
| 默认网页 | /usr/local/nginx/html/ |
| 日志 | /var/log/nginx/ |
| PID 文件 | /run/nginx.pid |
✅ 建议在
nginx.conf中添加:
http {
include /etc/nginx/conf.d/*.conf;
...
}
九、清理临时文件(可选)
cd /tmp
rm -rf nginx-${NGINX_VERSION}*
十、访问测试
浏览器打开:
http://你的服务器IP
应看到 “Welcome to nginx!” 页面。