nginx编译安装

生产环境中一般不建议使用yum方法来安装nginx,通常情况下需要通过编译安装方式来安装,二进制包下载地址:

http://nginx.org/en/download.html                 #二进制包
https://nginx.org/packages/centos/7/x86_64/RPMS/  #rpm包

先安装基础编译环境,执行命令如下:

yum -y install gcc gcc-c++ autoconf automake make zlib* pcre*  #centos
apt update && apt install build-essential  libpcre3 libpcre3-dev  openssl libssl-dev zlib1g-dev gcc  #ubuntu

1、首先将nginx安装包上传到linux服务器上,解压,进入解压后的目录中,执行命令如下:

上图中的安装目录可以根据需要自定义,如果添加模块,可以这样:./configure –prefix=/usr/local/nginx –with-stream,表示编译模块stream(此模块可以代理tcp或者udp)

添加多个功能包的编译如下(下面是基于nginx1.26):

./configure --prefix=/usr/local/nginx --with-http_ssl_module --with-http_v2_module --with-http_realip_module --with-http_sub_module --with-http_addition_module --with-stream_ssl_module --with-stream --with-http_secure_link_module --with-http_gzip_static_module --with-threads --with-file-aio
  • --with-http_ssl_module:启用 HTTPS/SSL 支持(必备)
  • --with-http_v2_module:支持 HTTP/2 协议,nginx1.9.5版本后才支持
  • --with-http_realip_module: 获取客户端真实 IP
  • --with-http_addition_module:响应内容追加文本
  • --with-http_sub_module:响应内容替换
  • --with-stream_ssl_module:加密的 TCP/UDP 代理,1.9.4版本后支持
  • --with-stream:TCP/UDP 代理支持(四层负载均衡),1.9.0版本后支持
  • --with-http_secure_link_module:资源访问权限控制(通过加密链接)
  • --with-http_gzip_static_module:预压缩静态文件(减少 CPU 开销)
  • --with-threads:启用线程池(提高性能)
  • --with-file-aio:启用异步文件 I/O(提升高并发性能)

2、编译完成后执行命令make && make install 安装,如图:

3、进入/usr/local/nginx/sbin目录执行命令./nginx启动nginx ,浏览器访问,如图:

4、配置服务自启动文件,编辑文件vim /lib/systemd/system/nginx.service,添加内容如图:

[Unit]
Description=nginx
Documentation=http://nginx.org/en/docs/
After=network.target remote-fs.target nss-lookup.target


[Service]
Type=forking
#ExecStartPre=/usr/local/nginx/sbin/nginx -t -c /usr/local/nginx/conf/nginx.conf
ExecStart=/usr/local/nginx/sbin/nginx -c /usr/local/nginx/conf/nginx.conf
ExecReload=/usr/local/nginx/sbin/nginx -s reload
ExecStop=/usr/local/nginx/sbin/nginx -s stop

[Install]
WantedBy=multi-user.target

配置完成后即可通过服务方式启动和停止nginx,命令如下:

systemctl restart nginx
systemctl status nginx
systemctl enable nginx
systemctl start nginx
systemctl stop nginx
systemctl relaod nginx

备注:如果修改了nginx配置文件后,想查看配置是否正确,可执行命令nginx -t查看,如图:

一键安装脚本内容如下:

#!/bin/bash
: '
 @function: 安装nginx,本例子中版本为nginx-1.21.6.tar.gz
 @author: gongguan
 @date: 2022-03-07
'
echo "<<<<<<<<<<<<<<<<<<首先安装基础编译环境>>>>>>>>>>>>>>>>>"
yum -y install gcc gcc-c++ autoconf automake make pcre* zlib*
[ $? -eq 0 ] && echo "<<<<<<<<<<<<<环境安装完成>>>>>>>>>>>>>"
tar -xf $(dirname $0)/nginx-1.21.6.tar.gz
cd nginx-1.21.6
./configure --prefix=/usr/local/nginx --with-stream --with-http_secure_link_module
[ $? -eq 0 ] && echo "<<<<<<<<<<<<<<<编译完成>>>>>>>>>>>>>"
make && make install
[ $? -eq 0 ] && echo "<<<<<<<<<<<<<安装完成>>>>>>>>>>>>>"
echo "<<<<<<<<<<<<<<<<添加软链接>>>>>>>>>>>>>>>>>>>>>>>>"
ln -s /usr/local/nginx/sbin/nginx /usr/bin/nginx
echo "<<<<<<<<<<<<<<<<<<<编写服务器托管文件>>>>>>>>>>>>>"
cat > /lib/systemd/system/nginx.service <<EOF
[Unit]
Description=nginx
Documentation=http://nginx.org/en/docs/
After=network.target remote-fs.target nss-lookup.target


[Service]
Type=forking
#ExecStartPre=/usr/local/nginx/sbin/nginx -t -c /usr/local/nginx/conf/nginx.conf
ExecStart=/usr/local/nginx/sbin/nginx -c /usr/local/nginx/conf/nginx.conf
ExecReload=/usr/local/nginx/sbin/nginx -s reload
ExecStop=/usr/local/nginx/sbin/nginx -s stop

[Install]
WantedBy=multi-user.target
EOF
echo "添加开机自启动"
systemctl enable nginx
systemctl start nginx
systemctl status nginx
  • –with-http_secure_link_module:用于配置防盗链
  • –with-stream:用于代理TCP和UDP

注意:如果nginx出现中文乱码,可以设置编码为UTF-8,在nginx.conf配置中添加如下:

charset utf-8;

要在日志中输出获取的真实IP,需要在http块中添加如下配置(需要http_realip_module模块):

# 确保设置$http_x_forwarded_for,该变量用于记录X-Forwarded-For的值
  log_format  main  '$remote_addr- $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';

附加

生产环境下nginx.conf配置文件内容如下:

user nginx;
worker_processes auto;

error_log /var/log/nginx/error.log warn;
pid /run/nginx.pid;

events {
    worker_connections 4096;
}

http {
    include /etc/nginx/mime.types;
    default_type application/octet-stream;
    #定义日志格式
    log_format main
        '$remote_addr - $host [$time_local] '
        '"$request" $status $body_bytes_sent '
        'rt=$request_time '
        'urt=$upstream_response_time';

    access_log /var/log/nginx/access.log main;

    sendfile on;
    tcp_nopush on;
    tcp_nodelay off;

    keepalive_timeout 65;
    keepalive_requests 100;
    client_max_body_size 50m;
    server_tokens off;

    gzip on;
    gzip_min_length 1k;
    gzip_types
        text/plain
        text/css
        application/json
        application/javascript
        application/xml;

    upstream app_backend {
        server 127.0.0.1:8080;
        server 127.0.0.1:8081;
    }

    server {
        listen 80;
        server_name example.com www.example.com;

        location /api/ {
            proxy_pass http://app_backend;

            proxy_http_version 1.1;
            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 5s;
            proxy_send_timeout 60s;
            proxy_read_timeout 60s;

            sendfile off;         #覆盖全局
            tcp_nopush off;       #覆盖全局配置
            tcp_nodelay on;       #覆盖全局
            proxy_tcp_nodelay on;
        }

        location /static/ {
            alias /var/www/static/;
            expires 7d;
            access_log off;
            #静态资源配置里已经默认使用http{}中的sendfile 和 tcp_nopush配置
        }

        error_page 404 /404.html;
        error_page 500 502 503 504 /50x.html;
    }
}
  • user nginx; #master进程是root启动,worker进程是nginx用户启动,如果nginx的端口在1-1023,必须使用root用户启动,否则不要求必须root,不建议设置user root;
  • worker_processes auto; #指定worker进程数量,配置为auto后会根据CPU核心数自动设置
  • worker_connections 4096; #每个 worker 进程允许的最大连接数,理论上最大连接数为:worker_processes × worker_connections
  • sendfile on; # 启用高效文件传输机制,减少文件在用户态和内核态之间的复制,只能处理静态文件,比如本地的文件,不能处理proxy_pass调用的后端服务,因为后端是动态的,sendfile会直接失效
  • tcp_nopush on; #配合 sendfile 使用,尽量将响应头和文件数据一次性发送,提高网络传输效率
  • tcp_nodelay on; #有数据马上发,降低延迟发送,适合需要低延迟响应的场景,通常在长连接启用时比较常见,比如调用websocket,调用后端/api服务,tcp_nodelay 一般直接配置在proxy_pass调用的后端服务里就行了
  • proxy_tcp_nodelay on; # tcp_nodelay on用于控制 客户端 <==> Nginx 的连接,proxy_tcp_nodelay on 专门控制 Nginx <==> 后端上游服务 的 TCP 连接,和tcp_nodelay on 配合使用
  • keepalive_timeout 65; #设置 HTTP 长连接的超时时间,单位为秒,客户端在这段时间内没有新请求,连接可能会被关闭,再次请求的时候又要重新建立TCP连接,不会复用之前的,如果在65s内再次发请求,那就复用之前建立的TCP连接,可以提高效率,keepalive_timeout 只针对普通 HTTP/HTTPS,对WebSocket无效,WebSocket 是升级后的长连接,不走 http keep‑alive 逻辑,它的超时看proxy_read_timeout 300s;
  • keepalive_requests 100; #同一条长连接上面,最多处理 100 次 http 请求,不管时间到没到,到达数量直接关闭连接,防止某一个客户端无限复用一条连接,做一些恶意行为
  • client_max_body_size #限制客户端请求体的最大大小,常用于限制文件上传大小
  • server_tokens off; #是否在错误页面和响应头中显示 Nginx 版本号,建议关闭,可以减少暴露服务版本信息
  • proxy_set_header X-Forwarded-Proto $scheme; #原始客户端访问使用的协议(http /https)传递给后端应用服务,如果用户通过HTTP访问 $scheme就是http否则就是https,后端可根据这个协议做拼接URL或者判断是否是安全链接,进行具体的业务逻辑
  • proxy_set_header Host $host; #把浏览器实际访问的域名,通过请求头Host传递给后端服务,如果不配置这个,发送给后端的HTTP 头部地址就是127.0.0.1:8080,后端如果有多域名服务,就会找不到域名,或者回调地址拼接、其他地址拼接的时候就会出差错,导致404