本文档详细记录从零开始编译安装 nginx、基础配置、安全加固、性能优化及运维管理的完整流程。
安装目标路径:/data/nginx
源码版本:nginx-1.30.4(可替换为其他稳定版)
1. 环境准备
1.1 操作系统
支持主流 linux 发行版(centos / rhel / ubuntu / debian / rocky linux 等)。
以下命令均以 root 或具有 sudo 权限的用户执行。
1.2 安装编译依赖
nginx 依赖 pcre(正则)、zlib(压缩)、openssl(https)等库的开发包。
ubuntu / debian
sudo apt update sudo apt install -y build-essential libpcre3-dev zlib1g-dev libssl-dev
centos / rhel / rocky linux
# 使用 yum sudo yum groupinstall -y "development tools" sudo yum install -y pcre-devel zlib-devel openssl-devel # 或使用 dnf sudo dnf groupinstall -y "development tools" sudo dnf install -y pcre-devel zlib-devel openssl-devel
验证依赖
gcc --version # 编译器 make --version pcre-config --version # 可选
2. 下载与解压源码
cd /data wget http://nginx.org/download/nginx-1.30.4.tar.gz tar -zxvf nginx-1.30.4.tar.gz cd nginx-1.30.4
注意:若需其他版本,可访问 http://nginx.org/download/ 获取。
3. 编译安装
3.1 配置编译选项
核心参数为 --prefix=/data/nginx,其他常用模块按需开启。
./configure --prefix=/data/nginx \
--with-http_ssl_module \
--with-http_v2_module \
--with-threads \
--with-stream \
--with-http_realip_module \
--with-http_gzip_static_module \
--with-http_stub_status_module \
--with-pcre \
--with-zlib \
--with-openssl=/usr/local/ssl # 若系统有独立openssl路径可指定参数说明
| 参数 | 作用 |
|---|---|
--prefix | 指定安装目录 |
--with-http_ssl_module | 启用 https 支持 |
--with-http_v2_module | 启用 http/2 |
--with-threads | 启用线程池 |
--with-stream | 四层负载均衡(tcp/udp) |
--with-http_realip_module | 获取客户端真实 ip(配合代理) |
--with-http_gzip_static_module | 预压缩静态文件 |
--with-http_stub_status_module | 提供状态监控页面 |
--with-pcre | 强制使用 pcre 库 |
--with-zlib | 强制使用 zlib 库 |
--with-openssl | 指定 openssl 源码路径(若需自定义版本) |
提示:执行
./configure --help可查看全部选项。
3.2 编译与安装
# 利用多核加速编译(nproc 获取 cpu 核心数) make -j$(nproc) # 安装(若目录无权限则加 sudo) sudo make install
3.3 验证安装
/data/nginx/sbin/nginx -v
应输出编译参数及版本信息。
4. 基础配置
4.1 配置文件结构
安装后目录结构:
/data/nginx/ ├── conf/ │ ├── nginx.conf # 主配置文件 │ ├── mime.types │ └── fastcgi_params # 及其他参数文件 ├── sbin/ │ └── nginx # 可执行文件 ├── html/ # 默认站点根目录(可修改) ├── logs/ # 日志目录(访问日志、错误日志) └── ...(其他目录)
4.2 最小化配置示例
编辑 /data/nginx/conf/nginx.conf:
# 运行用户(可选,建议用 nginx 用户)
user nobody;
# worker进程数,一般等于cpu核心数
worker_processes auto;
error_log /data/nginx/logs/error.log notice;
pid /data/nginx/logs/nginx.pid;
events {
worker_connections 1024; # 每个worker最大连接数
use epoll; # linux下使用epoll
}
http {
include /data/nginx/conf/mime.types;
default_type application/octet-stream;
# 日志格式定义
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
access_log /data/nginx/logs/access.log main;
sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 65;
types_hash_max_size 2048;
# 启用gzip压缩
gzip on;
gzip_vary on;
gzip_proxied any;
gzip_comp_level 6;
gzip_types text/plain text/css text/xml text/javascript application/json application/javascript application/xml+rss image/svg+xml;
# 第一个虚拟主机
server {
listen 80;
server_name localhost;
root /data/nginx/html;
index index.html index.htm;
# 自定义错误页面(可选)
error_page 404 /404.html;
location = /404.html {
internal;
}
}
# 可在此添加更多 server 块(虚拟主机)
}4.3 测试配置文件
修改后检查语法是否正确:
/data/nginx/sbin/nginx -t
5. 屏蔽版本号信息
5.1 方法一:配置文件(快速)
在 http 块中添加:
server_tokens off;
效果:响应头 server: nginx(无版本号),且错误页面不显示版本。
5.2 方法二:修改源码(彻底隐藏/自定义)
若需完全隐藏或修改 server 头内容,需重新编译。
编辑 src/core/nginx.h:
#define nginx_version "0.0.0" #define nginx_ver "customserver/" nginx_version
或直接固定字符串:
#define nginx_ver "mywebserver"
重新编译安装(参考第3节),注意备份原有配置文件。
6. 启动与管理
6.1 直接启动
/data/nginx/sbin/nginx
6.2 管理信号
# 快速停止 /data/nginx/sbin/nginx -s stop # 优雅停止(完成当前请求后退出) /data/nginx/sbin/nginx -s quit # 重载配置(不停服) /data/nginx/sbin/nginx -s reload # 重新打开日志文件(日志切割用) /data/nginx/sbin/nginx -s reopen
6.3 检查运行状态
ps -ef | grep nginx netstat -tlnp | grep :80
7. 设置开机自启
7.1 使用 systemd(推荐,适用于大多数现代 linux)
创建 /etc/systemd/system/nginx.service 文件:
[unit] description=nginx http server after=network.target [service] type=forking pidfile=/data/nginx/logs/nginx.pid execstartpre=/data/nginx/sbin/nginx -t execstart=/data/nginx/sbin/nginx execreload=/data/nginx/sbin/nginx -s reload execstop=/data/nginx/sbin/nginx -s stop privatetmp=true [install] wantedby=multi-user.target
启用并启动:
sudo systemctl daemon-reload sudo systemctl enable nginx sudo systemctl start nginx
7.2 使用 sysv init(旧系统)
创建 /etc/init.d/nginx 脚本(可参考网络模板),然后:
chmod +x /etc/init.d/nginx chkconfig --add nginx chkconfig nginx on
8. 日志管理
8.1 日志位置
- 访问日志:
/data/nginx/logs/access.log - 错误日志:
/data/nginx/logs/error.log
8.2 日志轮转(logrotate)
创建 /etc/logrotate.d/nginx:
/data/nginx/logs/*.log {
daily
missingok
rotate 52
compress
delaycompress
notifempty
create 0640 nobody nobody
sharedscripts
postrotate
[ -f /data/nginx/logs/nginx.pid ] && kill -usr1 `cat /data/nginx/logs/nginx.pid`
endscript
}测试轮转:
sudo logrotate -vf /etc/logrotate.d/nginx
9. 性能调优
9.1 调整 worker 进程和连接数
worker_processes auto:自动匹配 cpu 核心数。worker_connections:根据系统限制调整(如ulimit -n)。- 设置
worker_rlimit_nofile提高文件描述符上限:worker_rlimit_nofile 65535;
9.2 启用高效传输模式
sendfile on; tcp_nopush on; # 与 sendfile 配合 tcp_nodelay on; # 禁用 nagle 算法
9.3 调整 keepalive
keepalive_timeout 65; # 客户端保持时间 keepalive_requests 100; # 单个连接最大请求数
9.4 缓存与缓冲区
client_body_buffer_size 128k; client_max_body_size 8m; # 最大上传文件大小 client_header_buffer_size 1k; large_client_header_buffers 4 8k;
9.5 启用 gzip 压缩(已在前文配置)
可进一步提升传输效率。
9.6 使用缓存(proxy_cache 等)
若作为反向代理,可配置缓存以降低后端压力。
10. 安全加固
10.1 隐藏版本号(见第5节)
10.2 限制访问 ip
在 location 或 server 块中使用 allow/deny:
location /admin {
allow 192.168.1.0/24;
deny all;
}
10.3 禁用不必要的 http 方法
if ($request_method !~ ^(get|head|post)$ ) {
return 405;
}
10.4 设置安全头部
add_header x-frame-options "sameorigin" always; add_header x-content-type-options "nosniff" always; add_header x-xss-protection "1; mode=block" always; add_header strict-transport-security "max-age=31536000; includesubdomains" always;
10.5 限制请求频率(使用limit_req)
limit_req_zone $binary_remote_addr zone=one:10m rate=1r/s;
server {
location /api/ {
limit_req zone=one burst=5;
}
}
10.6 使用 https
若已编译 ssl 模块,配置证书并强制跳转:
server {
listen 443 ssl http2;
server_name example.com;
ssl_certificate /path/to/cert.pem;
ssl_certificate_key /path/to/key.pem;
ssl_protocols tlsv1.2 tlsv1.3;
# 其他 ssl 优化...
}
server {
listen 80;
server_name example.com;
return 301 https://$host$request_uri;
}
10.7 以普通用户运行
建议创建专门用户(如 nginx)而非 root:
user nginx;
创建用户:
sudo groupadd nginx sudo useradd -g nginx nginx
并确保日志、站点目录归属于该用户。
11. 常见问题排查
11.1 启动失败:端口被占用
查看 error.log,或使用:
sudo netstat -tlnp | grep :80
修改监听端口或结束占用进程。
11.2 权限错误(permission denied)
- 检查日志目录、站点根目录的用户权限是否与配置的
user一致。 - 确保 pid 文件目录可写。
11.3 403 forbidden
- 索引文件(index.html)是否存在?
- 目录是否有执行权限?(
chmod +x目录) - selinux 或 apparmor 可能阻止访问,可临时关闭测试(
setenforce 0)或设置规则。
11.4 502 bad gateway(反向代理场景)
- 后端服务未启动或端口错误。
- 检查
proxy_pass地址及连接超时设置。
11.5 配置文件错误
每次修改后务必执行:
/data/nginx/sbin/nginx -t
11.6 日志不记录或切割失效
- 检查日志路径权限。
- 确认
logrotate脚本中的postrotate信号正确。
12. 附录:常用编译参数
以下为生产环境常用完整编译选项(可根据需要增减):
./configure --prefix=/data/nginx \
--user=nginx \
--group=nginx \
--with-http_ssl_module \
--with-http_v2_module \
--with-http_realip_module \
--with-http_addition_module \
--with-http_sub_module \
--with-http_dav_module \
--with-http_flv_module \
--with-http_mp4_module \
--with-http_gunzip_module \
--with-http_gzip_static_module \
--with-http_random_index_module \
--with-http_secure_link_module \
--with-http_stub_status_module \
--with-http_auth_request_module \
--with-http_slice_module \
--with-threads \
--with-stream \
--with-stream_ssl_module \
--with-stream_realip_module \
--with-file-aio \
--with-pcre \
--with-zlib \
--with-openssl-opt=enable-tls1_3 \
--with-compat到此这篇关于nginx 部署编译安装版详细教程的文章就介绍到这了,更多相关nginx编译安装内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论