nginx

关注公众号 jb51net

关闭
首页 > 网站技巧 > 服务器 > nginx > nginx编译安装

Nginx 部署编译安装版详细教程

作者:Baron X

要在服务器上部署Nginx的编译安装版,你需要遵循以下步骤,这个过程通常涉及到从源代码编译Nginx,并根据你的需求配置额外的模块,感兴趣的朋友跟随小编一起看看吧

本文档详细记录从零开始编译安装 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 日志位置

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 进程和连接数

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

locationserver 块中使用 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)

11.3 403 Forbidden

11.4 502 Bad Gateway(反向代理场景)

11.5 配置文件错误

每次修改后务必执行:

/data/nginx/sbin/nginx -t

11.6 日志不记录或切割失效

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编译安装内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文