编译安装Nginx及所需的依赖包以及常用插件

Nginx 全能优化版部署文档

1. 下载 Nginx 源码包

具体版本查看 Nginx 官方下载地址:http://nginx.org/download

wget http://nginx.org/download/nginx-1.17.10.tar.gz
tar xf nginx-1.17.10.tar.gz
cd nginx-1.17.10

2. 安装编译依赖包

根据你的系统执行对应命令:
CentOS 环境:
yum -y install gcc gcc-c++ make pcre-devel zlib-devel openssl-devel libtool
Ubuntu 环境:
apt-get install libpcre3 libpcre3-dev zlib1g-dev libssl-dev

3. 配置运行权限

创建禁止登录的系统用户运行 Nginx Worker:

useradd -r -s /sbin/nologin nginx

4. 优化版编译参数并编译安装(全能整合)

此配置整合了内容替换、HTTPS、四层转发、多核 CPU 及大硬盘 IO 优化:

./configure --prefix=/usr/local/nginx \
--user=nginx \
--group=nginx \
--with-http_stub_status_module \
--with-http_ssl_module \
--with-http_v2_module \
--with-http_sub_module \
--with-http_realip_module \
--with-http_flv_module \
--with-http_mp4_module \
--with-http_gzip_static_module \
--with-threads \
--with-file-aio \
--with-stream \
--with-stream_realip_module \
--with-stream_ssl_module && make -j $(nproc) && make install

5. 高速编译与安装,上部分已包含

利用 nproc 自动获取 CPU 核心数进行并行编译,极大缩短时间:

make -j $(nproc) && make install

5.1 权限初始化 (关键步骤)

确保 nginx 用户对安装目录有完整的读写权限,防止启动或运行报错
chown -R nginx:nginx /usr/local/nginx

6. 环境变量设置

echo 'export PATH=$PATH:/usr/local/nginx/sbin' >> /etc/profile
source /etc/profile

检查并启动

/usr/local/nginx/sbin/nginx -t
/usr/local/nginx/sbin/nginx

最好用绝对路径的方式启动,后续需要升级nginx的话可以直接make upgrade;
当以普通用户执行sudo nginx的话会报找不到命令,是因为默认sudo会读取默认path安全路径,不会读取profile里的值,非root需要就需要sudo /usr/local/nginx/sbin/nginx来启动。

实战配置参考

优化nginx.conf

# ===== 全局配置(兼容源码/yum安装,适配所有服务器)=====
# 1. 运行用户:
# - 源码安装(/usr/local/nginx):默认用nobody(nginx源码编译默认用户)
# - YUM安装(/etc/nginx):改为nginx(yum安装自动创建nginx用户)
user  nginx;

# 工作进程数:auto自动匹配CPU核心(低配1核=1,高配多核自动适配)
worker_processes  auto;

# 错误日志路径:
# - 源码安装默认:/usr/local/nginx/logs/error.log
# - YUM安装默认:/etc/nginx/logs/error.log 或 /var/log/nginx/error.log
error_log  /usr/local/nginx/logs/error.log warn;
# YUM安装注释替换:
# error_log  /var/log/nginx/error.log warn;

# PID文件路径:
pid        /usr/local/nginx/logs/nginx.pid;
# YUM安装注释替换:
# pid        /var/run/nginx.pid;

# ===== 事件模块(性能优化核心)=====
events {
    # 单个进程最大连接数:低配1024足够,高配可提至4096
    worker_connections  1024;
    # 高性能IO模型(Linux专属)
    use epoll;
    # 一次性接收所有新连接(减少CPU消耗)
    multi_accept on;
}

# ===== HTTP核心配置(通用优化,修正mime.types路径位置)=====
http {
    # 2. MIME类型映射:优先适配源码安装路径,YUM安装路径注释备用
    # 源码安装默认路径(必须放在http块最顶部,否则会报错)
    include       /usr/local/nginx/conf/mime.types;
    # YUM安装注释替换:
    # include       /etc/nginx/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  /usr/local/nginx/logs/access.log  main;
    # YUM安装注释替换:
    # access_log  /var/log/nginx/access.log  main;

    # ===== 通用性能优化(所有服务器必开)=====
    sendfile        on;        # 高效文件传输
    tcp_nopush      on;        # 减少TCP报文段
    tcp_nodelay     on;        # 提高实时性
    keepalive_timeout  65;     # 长连接超时
    keepalive_requests 100;    # 长连接最大请求数
    client_header_timeout 10s; # 客户端请求头超时
    client_body_timeout 10s;   # 客户端请求体超时
    send_timeout 10s;          # 响应超时

    # ===== Gzip压缩(平衡压缩比和CPU消耗)=====
    gzip  on;
    gzip_vary on;
    gzip_min_length 1024;
    gzip_comp_level 4;         # 低配2-4,高配6-8
    gzip_proxied any;
    gzip_types
        text/plain
        text/css
        text/xml
        text/javascript
        application/json
        application/javascript
        application/xml+rss
        application/xhtml+xml
        image/svg+xml;

    # ===== 限流防护(可选,低配可注释)=====
    limit_conn_zone $binary_remote_addr zone=perip:10m;
    limit_conn perip 20;
    limit_req_zone $binary_remote_addr zone=req_limit:10m rate=10r/s;
    limit_req zone=req_limit burst=20 nodelay;

    # ===== 安全防护(通用)=====
    add_header X-Frame-Options "SAMEORIGIN" always;
    add_header X-XSS-Protection "1; mode=block" always;
    add_header X-Content-Type-Options "nosniff" always;

    # ===== 默认服务器配置(核心,适配源码安装路径)=====
    server {
        listen       81 default_server;         # 避开k3s劫持的80端口
        listen       [::]:81 default_server;
        server_name  _;

        # 网站根目录:
        # 源码安装默认:/usr/local/nginx/html
        root         /usr/local/nginx/html;
        # YUM安装注释替换:
        # root         /usr/share/nginx/html;

        # 默认首页
        index        index.html index.htm index.php;

        # 核心路由规则
        location / {
            try_files $uri $uri/ =404;
            expires 7d;  # 静态文件缓存7天
        }

        # ========== 新增:proxy_pass 基础示例(代理本地后端服务)==========
        # 场景1:将 /api 路径代理到本地8080端口的后端服务(无路径重写)
        location /api/ {
            # 代理目标地址(末尾带/,会把/api/后面的路径拼接过去)
            proxy_pass http://127.0.0.1:8080/;
            
            # 代理核心优化参数(必加,避免超时/连接异常)
            proxy_set_header Host $host;                  # 传递真实域名
            proxy_set_header X-Real-IP $remote_addr;      # 传递真实客户端IP
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; # 透传IP链
            proxy_set_header X-Forwarded-Proto $scheme;   # 传递协议(http/https)
            
            # 代理超时配置(按需调整)
            proxy_connect_timeout 30s;    # 连接后端超时
            proxy_send_timeout 30s;       # 发送数据到后端超时
            proxy_read_timeout 60s;       # 读取后端响应超时
            
            # 缓冲区配置(优化大请求/响应)
            proxy_buffering on;
            proxy_buffer_size 4k;         # 单个缓冲区大小
            proxy_buffers 8 4k;           # 缓冲区数量+大小
            proxy_busy_buffers_size 8k;   # 忙时缓冲区大小
        }

        # 场景2:将 /web 路径代理到远程服务器(带路径重写)
        location /web/ {
            # 代理目标地址(末尾不带/,会保留/web路径传递给后端)
            proxy_pass http://192.168.1.100:8090;
            
            # 同上,核心代理头信息
            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header X-Forwarded-Proto $scheme;
            
            # 超时配置
            proxy_connect_timeout 30s;
            proxy_send_timeout 30s;
            proxy_read_timeout 60s;
        }

        # 场景3:代理全部请求到后端服务(替换默认/路径)
        # 如需启用,注释原有location / {},取消以下注释
        # location / {
        #     proxy_pass http://127.0.0.1:3000;
        #     proxy_set_header Host $host;
        #     proxy_set_header X-Real-IP $remote_addr;
        #     proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        #     proxy_set_header X-Forwarded-Proto $scheme;
        #     proxy_connect_timeout 30s;
        #     proxy_send_timeout 30s;
        #     proxy_read_timeout 60s;
        # }

        # ========== proxy_pass 示例结束 ==========

        # 自定义错误页
        error_page 404 /404.html;
        location = /404.html {
            root /usr/local/nginx/html;
            # YUM安装注释替换:
            # root /usr/share/nginx/html;
            internal;
        }

        error_page 500 502 503 504 /50x.html;
        location = /50x.html {
            root /usr/local/nginx/html;
            # YUM安装注释替换:
            # root /usr/share/nginx/html;
            internal;
        }

        # 禁止访问隐藏文件
        location ~ /\. {
            deny all;
            access_log off;
            log_not_found off;
        }

        # 限制请求体大小
        client_max_body_size 10M;
    }

    # ===== 扩展配置(按需启用)=====
    # 1. PHP-FPM反向代理示例
    # location ~ \.php$ {
    #     fastcgi_pass   127.0.0.1:9000;
    #     fastcgi_index  index.php;
    #     fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
    #     include        /usr/local/nginx/conf/fastcgi_params;
    #     # YUM安装注释替换:
    #     # include        /etc/nginx/fastcgi_params;
    #     fastcgi_connect_timeout 5s;
    #     fastcgi_read_timeout 10s;
    # }

    # 2. HTTPS配置示例(整合proxy_pass)
    # server {
    #     listen       443 ssl http2;
    #     server_name  your-domain.com;
    #     # SSL证书路径
    #     ssl_certificate      /usr/local/nginx/conf/cert/your-domain.pem;
    #     ssl_certificate_key  /usr/local/nginx/conf/cert/your-domain.key;
    #     # YUM安装注释替换:
    #     # ssl_certificate      /etc/nginx/cert/your-domain.pem;
    #     # ssl_certificate_key  /etc/nginx/cert/your-domain.key;
    #     # SSL优化
    #     ssl_session_cache    shared:SSL:1m;
    #     ssl_session_timeout  10m;
    #     ssl_protocols TLSv1.2 TLSv1.3;
    #     ssl_ciphers ECDHE-RSA-AES256-GCM-SHA512:DHE-RSA-AES256-GCM-SHA512:ECDHE-RSA-AES256-GCM-SHA384:DHE-RSA-AES256-GCM-SHA384;
        
    #     # HTTPS下的proxy_pass示例(代理到http后端)
    #     location / {
    #         proxy_pass http://127.0.0.1:8080;
    #         proxy_set_header Host $host;
    #         proxy_set_header X-Real-IP $remote_addr;
    #         proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    #         proxy_set_header X-Forwarded-Proto https; # 告知后端是HTTPS请求
    #         proxy_connect_timeout 30s;
    #         proxy_send_timeout 30s;
    #         proxy_read_timeout 60s;
    #     }
    # }
}

字符串批量替换 (sub_filter):

location / {
    proxy_pass http://10.213.8.100:8070/maps/;
    proxy_set_header Accept-Encoding ""; 
    sub_filter 'http://webapi.amap.com' 'http://10.213.16.243:8081/webapi';
    sub_filter_types *;
    sub_filter_once off;
}

四层反向代理 (stream 模块):

stream {
    server {
        listen 12345 so_keepalive=on;
        proxy_pass 172.14.15.16:12345;
    }
}
posted @ 2020-10-09 17:45  开心burukku  阅读(2124)  评论(0)    收藏  举报