快速安装Nginx:Yum与源码编译指南

在本篇博客文章中,我们将介绍如何使用Yum(针对CentOS/RHEL)或Apt(针对Debian/Ubuntu)进行Nginx的快速安装,以及如何从源代码手动编译安装Nginx。无论你是初学者还是有经验的开发者,这篇文章都将为你提供清晰的指导。

nginx安装

Nginx版本和安装方式 Nginx 分为社区版和商业版,一般是社区版
Nginx版本
Mainline version 主要开发版本,一般为奇数版本号,比如1.19
Stable version 当前最新稳定版,一般为偶数版本,如:1.20
Legacy versions 旧的稳定版,一般为偶数版本,如:1.18
Nginx安装可以使用yum或源码安装,但是推荐使用源码编译安装
yum/apt的系统仓库版本比较旧。
编译安装可以更方便自定义相关路径,使用源码编译可以自定义相关功能,更方便业务的上的使用
docker 容器直接运行。
基于 yum 安装 Nginx。
查看系统和EPEL的nginx版本


[root@CentOS7 ~]# yum info nginx
Loaded plugins: fastestmirror, langpacks
Loading mirror speeds from cached hostfile
Available Packages
Name        : nginx
Arch        : x86_64
Epoch       : 1
Version     : 1.20.1
Release     : 10.el7
Size        : 588 k
Repo        : epl/7/x86_64
Summary     : A high performance web server and reverse proxy server
URL         : https://nginx.org
License     : BSD
Description : Nginx is a web server and a reverse proxy server for HTTP, SMTP, POP3 and
            : IMAP protocols, with a strong focus on high concurrency, performance and low
            : memory usage.
#配置好yum源
[root@rocky9 ~]# yum info nginx
Last metadata expiration check: 0:04:26 ago on Sun 24 Nov 2024 07:08:12 PM CST.
Available Packages
Name         : nginx
Epoch        : 2
Version      : 1.20.1
Release      : 20.el9.0.1
Architecture : x86_64
Size         : 36 k
Source       : nginx-1.20.1-20.el9.0.1.src.rpm
Repository   : AppStream
Summary      : A high performance web server and reverse proxy server
URL          : https://nginx.org
License      : BSD
Description  : Nginx is a web server and a reverse proxy server for HTTP, SMTP, POP3 and
             : IMAP protocols, with a strong focus on high concurrency, performance and low
             : memory usage.

官方包源安装最新版本 nginx

系统和EPEL源的中nignx版本较旧,可以安装官方源的最新版本
官方包链接


https://nginx.org/en/linux_packages.html

官方yum源链接


https://nginx.org/en/linux_packages.html#RHEL

通过官方 yum 源安装nginx


[root@rocky9 ~]# cat /etc/yum.repos.d/nginx.repo 
[nginx-stable]
name=nginx stable repo
baseurl=http://nginx.org/packages/centos/$releasever/$basearch/
gpgcheck=1
enabled=1
gpgkey=https://nginx.org/keys/nginx_signing.key
module_hotfixes=true

[nginx-mainline]
name=nginx mainline repo
baseurl=http://nginx.org/packages/mainline/centos/$releasever/$basearch/
gpgcheck=1
enabled=0
gpgkey=https://nginx.org/keys/nginx_signing.key
module_hotfixes=true

#列出所有版本
[root@rocky9 ~]# yum list nginx --showduplicates 
Last metadata expiration check: 11:23:50 ago on Sun 24 Nov 2024 07:51:01 AM CST.
Installed Packages
nginx.x86_64                                            2:1.26.2-2.el9.ngx                                             @nginx-stable
Available Packages
nginx.x86_64                                            1:1.20.2-1.el9.ngx                                             nginx-stable 
nginx.x86_64                                            1:1.22.0-1.el9.ngx                                             nginx-stable 
nginx.x86_64                                            1:1.22.1-1.el9.ngx                                             nginx-stable 
nginx.x86_64                                            1:1.24.0-1.el9.ngx                                             nginx-stable 
nginx.x86_64                                            1:1.26.0-1.el9.ngx                                             nginx-stable 
nginx.x86_64                                            1:1.26.1-1.el9.ngx                                             nginx-stable 
nginx.x86_64                                            1:1.26.1-2.el9.ngx                                             nginx-stable 
nginx.x86_64                                            1:1.26.2-1.el9.ngx                                             nginx-stable 
nginx.x86_64                                            2:1.20.1-20.el9.0.1                                            AppStream    
nginx.x86_64                                            2:1.26.2-2.el9.ngx   																					 nginx-stable 

[root@rocky9 ~]# yum info  nginx
Last metadata expiration check: 11:25:06 ago on Sun 24 Nov 2024 07:51:01 AM CST.
Installed Packages
Name         : nginx
Epoch        : 2
Version      : 1.26.2
Release      : 2.el9.ngx
Architecture : x86_64
Size         : 3.3 M
Source       : nginx-1.26.2-2.el9.ngx.src.rpm
Repository   : @System
From repo    : nginx-stable
Summary      : High performance web server
URL          : https://nginx.org/
License      : 2-clause BSD-like license
Description  : nginx [engine x] is an HTTP and reverse proxy server, as well as
             : a mail proxy server.

检查安装

查看nginx安装包信息


[root@rocky9 ~]# rpm -q nginx
nginx-1.26.2-2.el9.ngx.x86_64
[root@rocky9 ~]# rpm -ql nginx
/etc/logrotate.d/nginx
/etc/nginx
/etc/nginx/conf.d
/etc/nginx/conf.d/default.conf
/etc/nginx/fastcgi_params
/etc/nginx/mime.types
/etc/nginx/modules
/etc/nginx/nginx.conf
/etc/nginx/scgi_params
/etc/nginx/uwsgi_params
/usr/lib/.build-id
/usr/lib/.build-id/72
/usr/lib/.build-id/72/bec8458e615cfe0afcb1e79d97079566db7874
/usr/lib/.build-id/85
/usr/lib/.build-id/85/99ad49b8bc5512f5d3d2ec561b5732936bf62b
/usr/lib/systemd/system/nginx-debug.service
/usr/lib/systemd/system/nginx.service
/usr/lib64/nginx
/usr/lib64/nginx/modules
/usr/libexec/initscripts/legacy-actions/nginx
/usr/libexec/initscripts/legacy-actions/nginx/check-reload
/usr/libexec/initscripts/legacy-actions/nginx/upgrade
/usr/sbin/nginx
/usr/sbin/nginx-debug
/usr/share/doc/nginx-1.26.2
/usr/share/doc/nginx-1.26.2/COPYRIGHT
/usr/share/man/man8/nginx.8.gz
/usr/share/nginx
/usr/share/nginx/html
/usr/share/nginx/html/50x.html
/usr/share/nginx/html/index.html
/var/cache/nginx
/var/log/nginx

#带有自动日志切割功能
[root@rocky9 ~]# cat /etc/logrotate.d/nginx 
/var/log/nginx/*.log {
        daily
        missingok
        rotate 52
        compress
        delaycompress
        notifempty
        create 640 nginx adm
        sharedscripts
        postrotate
                if [ -f /var/run/nginx.pid ]; then
                        kill -USR1 `cat /var/run/nginx.pid`
                fi
        endscript
}
[root@rocky9 ~]# ls /var/log/nginx/
access.log  error.log

nginx用法帮助

使用yum源安装nginx


[root@rocky9 ~]# nginx -h
nginx version: nginx/1.26.2
Usage: nginx [-?hvVtTq] [-s signal] [-p prefix]
             [-e filename] [-c filename] [-g directives]

Options:
  -?,-h         : this help
  -v            : show version and exit
  -V            : show version and configure options then exit #显示版本和编译参数
  -t            : test configuration and exit 								 #测试配置文件是否异常
  -T            : test configuration, dump it and exit         #测试并打印
  -q            : suppress non-error messages during configuration testing  #静默模式
  -s signal     : send signal to a master process: stop, quit, reopen, reload  #发送信号,reload信号 会生成新的worker,但master不会重新生成
  -p prefix     : set prefix path (default: /etc/nginx/)				#指定nginx目录
  -e filename   : set error log file (default: /var/log/nginx/error.log) #日志目录 
  -c filename   : set configuration file (default: /etc/nginx/nginx.conf)   #配置文件路径
  -g directives : set global directives out of configuration file        #设置全局指令,注意和配置文件不要同时配置,否则冲突

nginx命令使用


[root@rocky9 ~]# vim /etc/nginx/nginx.conf 
user  nginx;
worker_processes  3;
[root@rocky9 ~]# ps auxf|grep nginx
root        1564  0.0  0.1   6408  2176 pts/0    S+   19:32   0:00              _ grep --color=auto nginx
root         764  0.0  0.2  11456  5148 ?        Ss   18:49   0:00 nginx: master process /usr/sbin/nginx -c /etc/nginx/nginx.conf
nginx       1560  0.0  0.3  15224  5404 ?        S    19:32   0:00  _ nginx: worker process
nginx       1561  0.0  0.3  15224  5404 ?        S    19:32   0:00  _ nginx: worker process
nginx       1562  0.0  0.3  15224  5404 ?        S    19:32   0:00  _ nginx: worker process

验证nginx


[root@rocky9 ~]# nginx -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
[root@rocky9 ~]# nginx -V
nginx version: nginx/1.26.2
built by gcc 11.4.1 20231218 (Red Hat 11.4.1-3) (GCC) 
built with OpenSSL 3.0.7 1 Nov 2022
TLS SNI support enabled
configure arguments: --prefix=/etc/nginx --sbin-path=/usr/sbin/nginx 
--modules-path=/usr/lib64/nginx/modules --conf-path=/etc/nginx/nginx.conf 
--error-log-path=/var/log/nginx/error.log --http-log-path=/var/log/nginx/access.log 
--pid-path=/var/run/nginx.pid --lock-path=/var/run/nginx.lock --http-client-body-temp-path=/var/cache/nginx/client_temp 
--http-proxy-temp-path=/var/cache/nginx/proxy_temp --http-fastcgi-temp-path=/var/cache/nginx/fastcgi_temp 
--http-uwsgi-temp-path=/var/cache/nginx/uwsgi_temp --http-scgi-temp-path=/var/cache/nginx/scgi_temp 
--user=nginx --group=nginx --with-compat --with-file-aio --with-threads 
--with-http_addition_module --with-http_auth_request_module 
--with-http_dav_module --with-http_flv_module --with-http_gunzip_module 
--with-http_gzip_static_module --with-http_mp4_module --with-http_random_index_module 
--with-http_realip_module --with-http_secure_link_module --with-http_slice_module 
--with-http_ssl_module --with-http_stub_status_module --with-http_sub_module 
--with-http_v2_module --with-http_v3_module --with-mail --with-mail_ssl_module 
--with-stream --with-stream_realip_module --with-stream_ssl_module 
--with-stream_ssl_preread_module --with-cc-opt='-O2 -flto=auto -ffat-lto-objects -fexceptions -g -grecord-gcc-switches -pipe -Wall -Werror=format-security -Wp,-D_FORTIFY_SOURCE=2 -Wp,-D_GLIBCXX_ASSERTIONS -specs=/usr/lib/rpm/redhat/redhat-hardened-cc1 -fstack-protector-strong -specs=/usr/lib/rpm/redhat/redhat-annobin-cc1 -m64 -march=x86-64-v2 -mtune=generic -fasynchronous-unwind-tables -fstack-clash-protection -fcf-protection -fPIC' 
--with-ld-opt='-Wl,-z,relro -Wl,-z,now -pie'

nginx启动文件


[root@rocky9 ~]# cat /usr/lib/systemd/system/nginx.service 
[Unit]
Description=nginx - high performance web server
Documentation=http://nginx.org/en/docs/
After=network-online.target remote-fs.target nss-lookup.target
Wants=network-online.target

[Service]
Type=forking
PIDFile=/var/run/nginx.pid
ExecStart=/usr/sbin/nginx -c /etc/nginx/nginx.conf
ExecReload=/bin/sh -c "/bin/kill -s HUP $(/bin/cat /var/run/nginx.pid)"
ExecStop=/bin/sh -c "/bin/kill -s TERM $(/bin/cat /var/run/nginx.pid)"

[Install]
WantedBy=multi-user.target

nginx配置文件

查看配置文件列表


[root@rocky9 ~]# rpm -qc nginx
/etc/logrotate.d/nginx
/etc/nginx/conf.d/default.conf
/etc/nginx/fastcgi_params
/etc/nginx/mime.types
/etc/nginx/nginx.conf
/etc/nginx/scgi_params
/etc/nginx/uwsgi_params
[root@rocky9 ~]# tree /etc/nginx/
/etc/nginx/
├── conf.d
│   └── default.conf
├── fastcgi_params
├── mime.types
├── modules -> ../../usr/lib64/nginx/modules
├── nginx.conf
├── scgi_params
└── uwsgi_params

2 directories, 6 files

配置文件/etc/nginx/nginx.conf 默认配置


[root@rocky9 ~]# cat /etc/nginx/nginx.conf 
user  nginx;
worker_processes  3;

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

events {
    worker_connections  1024;
}

http {
    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  /var/log/nginx/access.log  main;

    sendfile        on;
    #tcp_nopush     on;

    keepalive_timeout  65;

    #gzip  on;

    include /etc/nginx/conf.d/*.conf;
}

启动nginx


[root@rocky9 ~]# systemctl enable --now nginx
[root@rocky9 ~]# systemctl status nginx
● nginx.service - nginx - high performance web server
     Loaded: loaded (/usr/lib/systemd/system/nginx.service; enabled; preset: disabled)
     Active: active (running) since Sun 2024-11-24 09:40:43 CST; 10h ago
       Docs: http://nginx.org/en/docs/
    Process: 754 ExecStart=/usr/sbin/nginx -c /etc/nginx/nginx.conf (code=exited, status=0/SUCCESS)
   Main PID: 764 (nginx)
      Tasks: 4 (limit: 10904)
     Memory: 6.5M
        CPU: 131ms
     CGroup: /system.slice/nginx.service
             ├─ 764 "nginx: master process /usr/sbin/nginx -c /etc/nginx/nginx.conf"
             ├─1560 "nginx: worker process"
             ├─1561 "nginx: worker process"
             └─1562 "nginx: worker process"

Nov 24 09:40:43 rocky9 systemd[1]: Starting nginx - high performance web server...
Nov 24 09:40:43 rocky9 systemd[1]: Started nginx - high performance web server.
[root@rocky9 ~]# ps aux|grep nginx
root         764  0.0  0.2  11456  5148 ?        Ss   18:49   0:00 nginx: master process /usr/sbin/nginx -c /etc/nginx/nginx.conf
nginx       1560  0.0  0.3  15224  5404 ?        S    19:32   0:00 nginx: worker process
nginx       1561  0.0  0.3  15224  5404 ?        S    19:32   0:00 nginx: worker process
nginx       1562  0.0  0.3  15224  5404 ?        S    19:32   0:00 nginx: worker process
root        1606  0.0  0.1   6408  2176 pts/0    S+   19:44   0:00 grep --color=auto nginx
[root@rocky9 ~]# ss -ntl
State          Recv-Q         Send-Q                 Local Address:Port                   Peer Address:Port         Process         
LISTEN         0              128                          0.0.0.0:22                          0.0.0.0:*                            
LISTEN         0              511                          0.0.0.0:80                          0.0.0.0:*                            
LISTEN         0              128                             [::]:22                             [::]:*                            

nginx编译安装

Nginx是由C语言编写而成,所以Nginx源码安装需要提前准备标准的编译器GCC(GNU Compiler collection),由GNU开发,并以GPL即LGPL许可,早期GCC原本只能处理C语言,所以原名为GNUC语言编译器,后来得到快速发展,还可以处理C++,Fortran,pascal,objective-C,java以及Ada等其他语言,此外还需要Automake工具,以完成自动创建Makefile文件,Nginx的一些模块需要依赖第三方库,比如: pcre(支持rewrite),zlib(支持gzip模块)和openssl(支持ssl模块)等。
官方源码包下载地址


https://nginx.org/en/download.html

编译安装


[root@rocky9 ~]# yum -y  install make gcc gcc-c++ libtool pcre pcre-devel zlib zlib-devel openssl openssl-devel perl-ExtUtils-Embed
[root@rocky9 ~]# useradd -s /sbin/nologin nginx
[root@rocky9 ~]# cd /usr/local/src/
[root@rocky9 src]# wget https://nginx.org/download/nginx-1.26.2.tar.gz
[root@rocky9 src]# tar -xf nginx-1.26.2.tar.gz 
[root@rocky9 src]# ls
nginx-1.26.2  nginx-1.26.2.tar.gz
[root@rocky9 src]# cd nginx-1.26.2/
[root@rocky9 nginx-1.26.2]#./configure --prefix=/app/nginx --user=nginx --group=nginx --with-http_ssl_module --with-http_v2_module  --with-http_realip_module  --with-http_stub_status_module --with-http_gzip_static_module --with-pcre --with-stream --with-stream_ssl_module --with-stream_realip_module 
[root@rocky9 nginx-1.26.2]#make && make install 
[root@rocky9 nginx-1.26.2]#chown -R nginx.nginx /app/nginx/
#生成目录
[root@rocky9 nginx-1.26.2]# ll /app/nginx/
total 4
drwxr-xr-x 2 nginx nginx 4096 Nov 24 20:54 conf
drwxr-xr-x 2 nginx nginx   40 Nov 24 20:16 html
drwxr-xr-x 2 nginx nginx   41 Nov 24 20:51 logs
drwxr-xr-x 2 nginx nginx   19 Nov 24 20:16 sbin

#conf:保存nginx所有的配置文件,其中nginx.conf是nginx服务器的最核心最主要的配置文件,其他
的.conf则是用来配置nginx相关的功能的,例如fastcgi功能使用的是fastcgi.conf和
fastcgi_params两个文件,配置文件一般都有一个样板配置文件,是以.default为后缀,使用时可将其复
制并将default后缀去掉即可。
#html目录中保存了nginx服务器的web文件,但是可以更改为其他目录保存web文件,另外还有一个50x的
web文件是默认的错误页面提示页面。
#logs:用来保存nginx服务器的访问日志错误日志等日志,logs目录可以放在其他路径,比
如/var/logs/nginx里面。
#sbin:保存nginx二进制启动脚本,可以接受不同的参数以实现不同的功能。

验证版本及编译参数


[root@rocky9 nginx-1.26.2]# ln -s /app/nginx/sbin/nginx /usr/bin/
#查看版本
[root@rocky9 nginx-1.26.2]# nginx -v
nginx version: nginx/1.26.2
#查看编译参数
[root@rocky9 nginx-1.26.2]# nginx -V
nginx version: nginx/1.26.2
built by gcc 11.5.0 20240719 (Red Hat 11.5.0-2) (GCC) 
built with OpenSSL 3.2.2 4 Jun 2024
TLS SNI support enabled
configure arguments: --prefix=/app/nginx --user=nginx --group=nginx --with-http_ssl_module --with-http_v2_module --with-http_realip_module --with-http_stub_status_module --with-http_gzip_static_module --with-pcre --with-stream --with-stream_ssl_module --with-stream_realip_module

启动和停止nginx


[root@rocky9 ~]# nginx                     
[root@rocky9 ~]# ss -ntl
State          Recv-Q         Send-Q                 Local Address:Port                   Peer Address:Port         Process         
LISTEN         0              128                          0.0.0.0:22                          0.0.0.0:*                            
LISTEN         0              511                          0.0.0.0:80                          0.0.0.0:*                            
LISTEN         0              128                             [::]:22                             [::]:*   
#停止nginx
[root@rocky9 ~]# nginx -s stop
[root@rocky9 ~]# ss -ntl
State          Recv-Q         Send-Q                 Local Address:Port                   Peer Address:Port         Process         
LISTEN         0              128                          0.0.0.0:22                          0.0.0.0:*                            
LISTEN         0              128                             [::]:22                             [::]:*         

创建nginx启动文件


#复制同一版本的nginx的yum安装生成的service文件
[root@rocky9 ~]# cat /usr/lib/systemd/system/nginx.service 
[Unit]
Description=nginx - high performance web server
Documentation=http://nginx.org/en/docs/
After=network-online.target remote-fs.target nss-lookup.target
Wants=network-online.target

[Service]
Type=forking
PIDFile=/app/nginx/run/nginx.pid   #指定pid文件的目录,默认在logs目录下,可选配置
ExecStart=/app/nginx/sbin/nginx -c /app/nginx/conf/nginx.conf
ExecReload=/bin/sh -c "/bin/kill -s HUP $(/bin/cat /app/nginx/run/nginx.pid)"
ExecStop=/bin/sh -c "/bin/kill -s TERM $(/bin/cat /app/nginx/run/nginx.pid)"

[Install]
WantedBy=multi-user.target
#创建pid文件存放的目录
[root@rocky9 ~]# mkdir /app/nginx/run/
#修改配置文件
[root@rocky9 ~]# vim /app/nginx/conf/nginx.conf
pid        /app/nginx/run/nginx.pid;  #和上面的pid文件路径一样

验证 Nginx 启动文件


[root@rocky9 ~]# systemctl daemon-reload 
[root@rocky9 ~]# systemctl enable --now nginx
[root@rocky9 ~]# ll /app/nginx/run/
total 4
-rw-r--r-- 1 root root 6 Nov 24 21:18 nginx.pid
[root@rocky9 ~]# ss -ntl
State          Recv-Q         Send-Q                 Local Address:Port                   Peer Address:Port         Process         
LISTEN         0              128                          0.0.0.0:22                          0.0.0.0:*                            
LISTEN         0              511                          0.0.0.0:80                          0.0.0.0:*                            
LISTEN         0              128                             [::]:22                             [::]:*  
[root@rocky9 ~]# systemctl status nginx.service 
● nginx.service - nginx - high performance web server
     Loaded: loaded (/usr/lib/systemd/system/nginx.service; enabled; preset: disabled)
     Active: active (running) since Sun 2024-11-24 21:18:12 CST; 34s ago
       Docs: http://nginx.org/en/docs/
    Process: 38109 ExecStart=/app/nginx/sbin/nginx -c /app/nginx/conf/nginx.conf (code=exited, status=0/SUCCESS)
   Main PID: 38110 (nginx)
      Tasks: 2 (limit: 10904)
     Memory: 1.9M
        CPU: 20ms
     CGroup: /system.slice/nginx.service
             ├─38110 "nginx: master process /app/nginx/sbin/nginx -c /app/nginx/conf/nginx.conf"
             └─38111 "nginx: worker process"

Nov 24 21:18:12 rocky9 systemd[1]: Starting nginx - high performance web server...
Nov 24 21:18:12 rocky9 systemd[1]: Started nginx - high performance web server.
[root@rocky9 ~]# systemctl stop nginx.service 
[root@rocky9 ~]# systemctl status nginx.service 
○ nginx.service - nginx - high performance web server
     Loaded: loaded (/usr/lib/systemd/system/nginx.service; enabled; preset: disabled)
     Active: inactive (dead) since Sun 2024-11-24 21:19:02 CST; 1s ago
   Duration: 49.941s
       Docs: http://nginx.org/en/docs/
    Process: 38109 ExecStart=/app/nginx/sbin/nginx -c /app/nginx/conf/nginx.conf (code=exited, status=0/SUCCESS)
    Process: 38146 ExecStop=/bin/sh -c /bin/kill -s TERM $(/bin/cat /app/nginx/run/nginx.pid) (code=exited, status=0/SUCCESS)
   Main PID: 38110 (code=exited, status=0/SUCCESS)
        CPU: 37ms

Nov 24 21:18:12 rocky9 systemd[1]: Starting nginx - high performance web server...
Nov 24 21:18:12 rocky9 systemd[1]: Started nginx - high performance web server.
Nov 24 21:19:02 rocky9 systemd[1]: Stopping nginx - high performance web server...
Nov 24 21:19:02 rocky9 systemd[1]: nginx.service: Deactivated successfully.
Nov 24 21:19:02 rocky9 systemd[1]: Stopped nginx - high performance web server.
[root@rocky9 ~]# ss -ntl
State          Recv-Q         Send-Q                 Local Address:Port                   Peer Address:Port         Process         
LISTEN         0              128                          0.0.0.0:22                          0.0.0.0:*                            
LISTEN         0              128                             [::]:22                             [::]:*                            

自动化部署nginx

一键安装 nginx 脚本


[root@ubuntu2404 ~]#cat install_nginx.sh
#!/bin/bash
NGINX_VERSION=1.28.0
NGINX_FILE=nginx-${NGINX_VERSION}.tar.gz
NGINX_INSTALL_DIR=/apps/nginx
SRC_DIR=/usr/local/src
CPUS=`lscpu |awk '/^CPU(s)/{print $2}'`

. /etc/os-release

install () {
    color "开始安装 nginx" 0
    if id nginx  &> /dev/null;then
        color "nginx 用户已存在" 1 
    else
        useradd -s /sbin/nologin -r  nginx
        color "创建 nginx 用户" 0 
    fi
    color "开始安装 nginx 依赖包" 0
    if [ $ID == "centos" ] ;then
	    if [[ $VERSION_ID =~ ^7 ]];then
            yum -y  install  gcc  make pcre-devel openssl-devel zlib-devel perl-ExtUtils-Embed
		elif [[ $VERSION_ID =~ ^8 ]];then
            yum -y  install make gcc-c++ libtool pcre pcre-devel zlib zlib-devel openssl openssl-devel perl-ExtUtils-Embed 
		else 
            color '不支持此系统!'  1
            exit
        fi
     elif [ $ID == "rocky"  ];then
	    yum -y  install gcc make gcc-c++ libtool pcre pcre-devel zlib zlib-devel openssl openssl-devel perl-ExtUtils-Embed 
     else
        apt update
        apt -y install gcc make  libpcre3 libpcre3-dev openssl libssl-dev zlib1g-dev
     fi
     [ $? -ne 0 ] && { color "安装依赖包失败" 1; exit; } 
     cd $SRC_DIR
     tar xf ${NGINX_FILE}
     NGINX_DIR=`echo ${NGINX_FILE}| sed -nr 's/^(.*[0-9]).*/1/p'`
     cd ${NGINX_DIR}
     ./configure --prefix=${NGINX_INSTALL_DIR} --user=nginx --group=nginx --with-http_ssl_module --with-http_v2_module --with-http_realip_module --with-http_stub_status_module --with-http_gzip_static_module --with-pcre --with-stream --with-stream_ssl_module --with-stream_realip_module 
     make -j $CPUS && make install 
     [ $? -eq 0 ] && color "nginx 编译安装成功" 0 ||  { color "nginx 编译安装失败,退出!" 1 ;exit; }
	 chown -R nginx:nginx ${NGINX_INSTALL_DIR}
     ln -s ${NGINX_INSTALL_DIR}/sbin/nginx /usr/local/sbin/nginx
     echo "PATH=${NGINX_INSTALL_DIR}/sbin:${PATH}" > /etc/profile.d/nginx.sh
     cat > /lib/systemd/system/nginx.service <<EOF
[Unit]
Description=The nginx HTTP and reverse proxy server
After=network.target remote-fs.target nss-lookup.target

[Service]
Type=forking
PIDFile=${NGINX_INSTALL_DIR}/logs/nginx.pid
ExecStartPre=/bin/rm -f ${NGINX_INSTALL_DIR}/logs/nginx.pid
ExecStartPre=${NGINX_INSTALL_DIR}/sbin/nginx -t
ExecStart=${NGINX_INSTALL_DIR}/sbin/nginx
ExecReload=/bin/kill -s HUP $MAINPID
KillSignal=SIGQUIT
TimeoutStopSec=5
KillMode=process
PrivateTmp=true
LimitNOFILE=100000

[Install]
WantedBy=multi-user.target
EOF
     systemctl daemon-reload
     systemctl enable --now nginx &> /dev/null 
     systemctl is-active nginx &> /dev/null ||  { color "nginx 启动失败,退出!" 1 ; exit; }
     color "nginx 安装完成" 0
}

install

结论
通过以上步骤,你可以选择适合自己的方式来安装Nginx。无论是简单快捷的yum/apt安装,还是灵活多变的源码编译安装,都能满足不同场景下的需求。希望这篇指南能帮助你顺利搭建起自己的Web服务器!

© 版权声明
THE END
如果内容对您有所帮助,就支持一下吧!
点赞0 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容