本文将指导如何在 Ubuntu 系统上编译 Nginx 并配置服务,包括安装依赖、编译参数配置、服务启动和测试等步骤。
准备工作
确保系统为 Ubuntu 20.04 或更高版本,并已更新到最新状态。使用以下命令更新系统:
sudo apt update && sudo apt upgrade -y
安装编译依赖
编译 Nginx 需要以下依赖包。使用以下命令安装:
sudo apt install build-essential libpcre3 libpcre3-dev libssl-dev libxml2-dev -y

下载 Nginx 源码
访问 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
编译 Nginx
进入源码目录后,使用 ./configure 脚本配置编译选项。以下是一个基本的配置示例:
./configure --prefix=/usr/local/nginx \
--with-http_ssl_module \
--with-http_stub_status_module \
--with-http_gzip_static_module \
--with-pcre
配置完成后,使用以下命令编译并安装:
make
sudo make install
配置 Nginx
编辑 Nginx 配置文件 /usr/local/nginx/conf/nginx.conf。以下是一个基本的配置示例:
user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log warn;
pid /var/run/nginx.pid;
events {
worker_connections 1024;
}
http {
include /usr/local/nginx/conf/mime.types;
default_type application/octet-stream;
sendfile on;
keepalive_timeout 65;
gzip on;
server {
listen 80;
server_name localhost;
root /usr/local/nginx/html;
location / {
try_files $uri $uri/ =404;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root /usr/local/nginx/html;
}
}
}
启动 Nginx 服务
使用以下命令启动 Nginx 服务:
sudo /usr/local/nginx/sbin/nginx
检查服务状态,确保 Nginx 正在运行:
sudo systemctl status nginx
测试 Nginx
在浏览器中访问 http://localhost,应看到 Nginx 的默认欢迎页面。如果出现问题,检查 /var/log/nginx/error.log 文件获取错误信息。
开机自启配置
使用以下命令使 Nginx 在系统启动时自动运行:
sudo systemctl enable nginx