Nginx介绍、架构和安装

文章目录

  • Nginx介绍、架构和安装
  • 1.Nginx介绍
  • 2.Nginx架构
  • 3.Nginx安装
    • 3.1 主机初始化
      • 3.1.1 设置网卡名和ip地址
      • 3.1.2 配置镜像源
      • 3.1.3 关闭防火墙
      • 3.1.4 禁用SELinux
      • 3.1.5 设置时区
    • 3.2 Nginx版本和安装方式
    • 3.3 包安装
      • 3.3.1 CentOS 安装
        • 3.3.1.1 查看当前系统中的 nginx 版本
        • 3.3.1.2 官方包源安装最新版本 nginx
        • 3.3.1.3 检查安装
        • 3.3.1.4 nginx 程序用法帮助
        • 3.3.1.5 验证 Nginx
        • 3.3.1.6 Nginx 启动文件
        • 3.3.1.7 Nginx 配置文件
        • 3.3.1.8 启动 Nginx
        • 3.3.1.9 访问 Nginx
      • 3.3.2 Ubuntu 安装
        • 3.3.2.1 查看当前系统中的 nginx 版本
        • 3.3.2.2 官方包源安装最新版本 nginx
        • 3.3.2.3 检查安装
        • 3.3.2.4 nginx 程序用法帮助
        • 3.3.2.5 验证 Nginx
        • 3.3.2.6 Nginx 启动文件
        • 3.3.2.7 Nginx 配置文件
        • 3.3.2.8 启动 Nginx
        • 3.3.2.9 访问 Nginx
    • 3.4 Nginx 编译安装
      • 3.4.1 编译安装 Nginx
      • 3.4.2 验证版本及编译参数
      • 3.4.3 启动和停止 nginx 测试访问 web 界面
      • 3.4.4 创建 Nginx 自启动文件
      • 3.4.5 验证 Nginx 自启动文件
      • 3.4.6 一键编译安装Nginx脚本

1.Nginx介绍

Nginx介绍、架构和安装-LMLPHP

Nginx(发音为"engine-x")是一个开源的高性能、轻量级的Web服务器和反向代理服务器。它由Igor Sysoev创建,并于2004年首次公开发布。Nginx的设计目标是提供高性能、稳定性和低资源消耗。

Nginx最初是为了解决C10k问题而开发的。C10k问题指的是服务器同时处理成千上万个并发连接的能力。Nginx采用了事件驱动、非阻塞的架构,通过使用少量的系统资源就能处理大量的并发连接。这使得Nginx能够在高负载下保持出色的性能表现。

Nginx的主要特点包括:

  1. 高性能:Nginx采用了异步非阻塞的事件驱动模型,能够高效地处理并发连接,具有出色的性能表现。它可以作为静态文件服务器,处理静态内容的请求速度非常快,并且能够有效地处理动态内容的请求。
  2. 反向代理:Nginx可以作为反向代理服务器,将客户端的请求转发给后端的多个服务器,实现负载均衡和高可用性。它可以根据不同的规则将请求分发给不同的后端服务器,提供更好的性能和可扩展性。
  3. 高可靠性:Nginx具有出色的稳定性和可靠性。它能够处理高并发的请求,并且在面对异常情况时能够保持稳定运行,不会因为单个请求的失败而导致整个系统的崩溃。
  4. 轻量级:Nginx的代码精简,占用的系统资源少。它可以在资源有限的环境中运行,对系统的负载较小。
  5. 扩展性:Nginx支持丰富的第三方模块和插件,可以通过添加模块来扩展其功能。它还提供了灵活的配置选项,可以根据需要进行自定义配置。

2.Nginx架构

Nginx广泛用于构建高性能的Web服务器、反向代理服务器、负载均衡器和缓存服务器。它被许多大型网站和互联网公司使用,如Netflix、Dropbox、GitHub等。同时,Nginx也是一个非常受欢迎的选择,用于部署现代化的Web应用程序和微服务架构。

Nginx的架构采用了事件驱动的模型,它由一个主进程和多个工作进程组成。下面是Nginx的典型架构示意图:

        Master Process
        ┌──────────────┐
        │              │
        │   Nginx      │
        │   Master     │
        │   Process    │
        │              │
        └──────────────┘
              │
              │
              ▼
        Worker Processes
        ┌──────────────┐
        │              │
        │   Nginx      │
        │   Worker     │
        │   Process    │
        │              │
        └──────────────┘
  1. 主进程(Master Process):主进程负责管理和控制工作进程。它读取配置文件,加载并初始化各个模块,创建和维护工作进程池,接收和处理来自工作进程的信号,以及监控工作进程的状态。
  2. 工作进程(Worker Process):工作进程是实际处理客户端请求的进程。主进程会创建多个工作进程,并将请求分发给它们。每个工作进程独立地处理请求,包括接收请求、解析请求、处理请求、生成响应,并将响应返回给客户端。工作进程之间相互独立,可以并行处理请求,提高系统的并发处理能力。

Nginx的事件驱动模型基于事件循环机制。主进程和工作进程都运行在事件循环中,等待事件的发生并进行处理。当有新的连接请求到达时,主进程接收到请求并将其分发给一个空闲的工作进程。工作进程通过非阻塞的方式处理连接,当连接关闭或请求处理完成时,工作进程将结果返回给客户端,并继续等待下一个事件。

Nginx的架构设计使得它能够高效地处理大量的并发连接,并具有良好的性能和可扩展性。它的事件驱动模型和非阻塞IO机制使得它能够充分利用系统资源,同时保持低的内存消耗和高的吞吐量。这使得Nginx成为一个非常适合构建高性能Web服务器和反向代理服务器的选择。

3.Nginx安装

3.1 主机初始化

3.1.1 设置网卡名和ip地址

Rocky 9和CentOS Stream 9:

# Rocky 9和CentOS Stream 9默认支持修改网卡名。
[root@rocky9 ~]# grep 'plugins' /etc/NetworkManager/NetworkManager.conf 
#plugins=keyfile,ifcfg-rh
# 因为网卡命名方式默认是keyfile,默认不支持修改网卡名,既然官方已经默认是keyfile那这里就不去更改网卡名了。

[root@rocky9 ~]# ETHNAME=`ip addr | awk -F"[ :]" '/^2/{print $3}'`

[root@rocky9 ~]# nmcli con delete ${ETHNAME} && nmcli connection add type ethernet con-name ${ETHNAME} ifname ${ETHNAME} ipv4.method manual ipv4.address "172.31.0.9/21" ipv4.gateway "172.31.0.2" ipv4.dns "223.5.5.5,180.76.76.76" autoconnect yes && nmcli con reload && nmcli con up ${ETHNAME}
# 172.31.0.9/21中172.31.0.9是ip地址,21是子网位数;172.31.0.2是网关地址;223.5.5.5, 180.76.76.76都是DNS,根据自己的需求修改。

[root@rocky9 ~]# ip addr
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet 127.0.0.1/8 scope host lo
       valid_lft forever preferred_lft forever
    inet6 ::1/128 scope host 
       valid_lft forever preferred_lft forever
2: ens160: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc mq state UP group default qlen 1000
    link/ether 00:0c:29:37:62:95 brd ff:ff:ff:ff:ff:ff
    altname enp3s0
    inet 172.31.0.9/21 brd 172.31.7.255 scope global noprefixroute ens160
       valid_lft forever preferred_lft forever
    inet6 fe80::51ca:fd5d:3552:677d/64 scope link noprefixroute 
       valid_lft forever preferred_lft forever
# 可以看到ip地址已修改。

Rocky 8、CentOS Stream 8和CentOS 7:

# Rocky 8、CentOS Stream 8和CentOS 7支持修改网卡名。
[root@rocky8 ~]# grep 'plugins' /etc/NetworkManager/NetworkManager.conf 
#plugins=ifcfg-rh
# 因为网卡命名方式默认是ifcfg-rh,支持修改网卡名。

# 修改网卡名称配置文件
[root@rocky8 ~]# sed -ri.bak '/^GRUB_CMDLINE_LINUX=/s@"$@ net.ifnames=0 biosdevname=0"@' /etc/default/grub
[root@rocky8 ~]# grub2-mkconfig -o /boot/grub2/grub.cfg
Generating grub configuration file ...
done

# 修改网卡文件名
[root@rocky8 ~]# ETHNAME=`ip addr | awk -F"[ :]" '/^2/{print $3}'`
[root@rocky8 ~]# mv /etc/sysconfig/network-scripts/ifcfg-${ETHNAME} /etc/sysconfig/network-scripts/ifcfg-eth0

[root@rocky8 ~]# shutdown -r now


[root@rocky8 ~]# nmcli dev
DEVICE  TYPE      STATE      CONNECTION         
eth0    ethernet  connected  Wired connection 1 
lo      loopback  unmanaged  --
# 可以看到CONNECTION的名字是Wired connection 1,要改名才可以下面设置。

[root@rocky8 ~]# ETHNAME=`ip addr | awk -F"[ :]" '/^2/{print $3}'`

[root@rocky8 ~]# nmcli connection modify "Wired connection 1" con-name ${ETHNAME}
[root@rocky8 ~]# nmcli dev
DEVICE  TYPE      STATE      CONNECTION 
eth0    ethernet  connected  eth0       
lo      loopback  unmanaged  --  

# 修改ip地址
[root@rocky8 ~]# nmcli con delete ${ETHNAME} && nmcli connection add type ethernet con-name ${ETHNAME} ifname ${ETHNAME} ipv4.method manual ipv4.address "172.31.0.8/21" ipv4.gateway "172.31.0.2" ipv4.dns "223.5.5.5,180.76.76.76" autoconnect yes && nmcli con reload && nmcli dev up eth0
# 172.31.0.8/21中172.31.0.8是ip地址,21是子网位数;172.31.0.2是网关地址;223.5.5.5, 180.76.76.76都是DNS,根据自己的需求修改。

[root@rocky8 ~]# ip addr
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet 127.0.0.1/8 scope host lo
       valid_lft forever preferred_lft forever
    inet6 ::1/128 scope host 
       valid_lft forever preferred_lft forever
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc mq state UP group default qlen 1000
    link/ether 00:0c:29:6f:65:d3 brd ff:ff:ff:ff:ff:ff
    altname enp3s0
    altname ens160
    inet 172.31.0.8/21 brd 172.31.7.255 scope global noprefixroute eth0
       valid_lft forever preferred_lft forever
    inet6 fe80::e9c9:aa93:4a58:2cc2/64 scope link noprefixroute 
       valid_lft forever preferred_lft forever
# 重启系统后可以看到网卡名已经修改成eth0,ip地址也已修改。

Ubuntu:

# Ubuntu先启用root用户,并设置密码
raymond@ubuntu2204:~$ cat set_root_login.sh 
#!/bin/bash

read -p "请输入密码: " PASSWORD
echo ${PASSWORD} |sudo -S sed -ri 's@#(PermitRootLogin )prohibit-password@\1yes@' /etc/ssh/sshd_config
sudo systemctl restart sshd
sudo -S passwd root <<-EOF
${PASSWORD}
${PASSWORD}
EOF

raymond@ubuntu2204:~$ bash set_root_login.sh 
请输入密码: 123456
[sudo] password for raymond: New password: Retype new password: passwd: password updated successfully

raymond@ubuntu2204:~$ rm -rf set_root_login.sh

# 使用root登陆,修改网卡名
root@ubuntu2204:~# sed -ri.bak '/^GRUB_CMDLINE_LINUX=/s@"$@net.ifnames=0 biosdevname=0"@' /etc/default/grub
root@ubuntu2204:~# grub-mkconfig -o /boot/grub/grub.cfg
Sourcing file `/etc/default/grub'
Sourcing file `/etc/default/grub.d/init-select.cfg'
Generating grub configuration file ...
Found linux image: /boot/vmlinuz-5.15.0-88-generic
Found initrd image: /boot/initrd.img-5.15.0-88-generic
Warning: os-prober will not be executed to detect other bootable partitions.
Systems on them will not be added to the GRUB boot configuration.
Check GRUB_DISABLE_OS_PROBER documentation entry.
done

# Ubuntu 20.04设置ip地址
root@ubuntu2004:~# cat > /etc/netplan/00-installer-config.yaml <<-EOF
network:
  version: 2
  renderer: networkd
  ethernets:
    eth0:
      dhcp4: no
      dhcp6: no
      addresses: [172.31.0.20/21] 
      gateway4: 172.31.0.2
      nameservers:
        addresses: [223.5.5.5, 180.76.76.76]
EOF
# 说明:Ubuntu20.04网卡配置文件是00-installer-config.yaml;172.31.0.20/21中172.31.0.20是ip地址,21是子网位数;172.31.0.2是网关地址;223.5.5.5, 180.76.76.76都是DNS,根据自己的需求修改。

# Ubuntu 18.04设置ip地址
root@ubuntu1804:~# cat > /etc/netplan/01-netcfg.yaml <<-EOF
network:
  version: 2
  renderer: networkd
  ethernets:
    eth0:
      dhcp4: no
      dhcp6: no
      addresses: [172.31.0.18/21] 
      gateway4: 172.31.0.2
      nameservers:
        addresses: [223.5.5.5, 180.76.76.76]
EOF
# 说明:Ubuntu18.04网卡配置文件是01-netcfg.yaml;172.31.0.18/21中172.31.0.18是ip地址,21是子网位数;172.31.0.2是网关地址;223.5.5.5, 180.76.76.76都是DNS,根据自己的需求修改。

root@ubuntu2004:~# shutdown -r now

root@ubuntu2004:~# ip addr
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet 127.0.0.1/8 scope host lo
       valid_lft forever preferred_lft forever
    inet6 ::1/128 scope host 
       valid_lft forever preferred_lft forever
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc fq_codel state UP group default qlen 1000
    link/ether 00:0c:29:e5:98:6f brd ff:ff:ff:ff:ff:ff
    inet 172.31.0.20/21 brd 172.31.7.255 scope global eth0
       valid_lft forever preferred_lft forever
    inet6 fe80::20c:29ff:fee5:986f/64 scope link 
       valid_lft forever preferred_lft forever
# 重启系统后可以看到网卡名已经修改成eth0,ip地址也已修改。

# Ubuntu 22.04设置ip地址
root@ubuntu2204:~# cat > /etc/netplan/00-installer-config.yaml <<-EOF
network:
  version: 2
  renderer: networkd
  ethernets:
    eth0:
      dhcp4: no
      dhcp6: no
      addresses: [172.31.0.22/21]
      routes:
        - to: default
          via: 172.31.0.2
      nameservers:
        addresses: [223.5.5.5, 180.76.76.76]
EOF
# 说明:Ubuntu 22.04网卡配置文件是00-installer-config.yaml;172.31.0.22/21中172.31.0.22是ip地址,21是子网位数;172.31.0.2是网关地址,Ubuntu 22.04设置网关地址的方法发生了改变,参考上面的方法;223.5.5.5, 180.76.76.76都是DNS,根据自己的需求修改。

root@ubuntu2204:~# shutdown -r now

# 重启后使用新设置的ip登陆
root@ubuntu2204:~# ip addr
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet 127.0.0.1/8 scope host lo
       valid_lft forever preferred_lft forever
    inet6 ::1/128 scope host 
       valid_lft forever preferred_lft forever
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc fq_codel state UP group default qlen 1000
    link/ether 00:0c:29:a7:be:f2 brd ff:ff:ff:ff:ff:ff
    altname enp2s1
    altname ens33
    inet 172.31.0.22/21 brd 172.31.7.255 scope global eth0
       valid_lft forever preferred_lft forever
    inet6 fe80::20c:29ff:fea7:bef2/64 scope link 
       valid_lft forever preferred_lft forever
# 重启系统后可以看到网卡名已经修改成eth0,ip地址也已修改。

3.1.2 配置镜像源

Rocky 8和9:

MIRROR=mirrors.sjtug.sjtu.edu.cn
sed -i.bak -e 's|^mirrorlist=|#mirrorlist=|g' -e 's|^#baseurl=http://dl.rockylinux.org/$contentdir|baseurl=https://'${MIRROR}'/rocky|g' /etc/yum.repos.d/[Rr]ocky*.repo

dnf clean all && dnf makecache

CentOS Stream 9:

cat update_mirror.pl
#!/usr/bin/perl

use strict;
use warnings;
use autodie;

# 要修改镜像源,请去修改url变量!
my $url = 'mirrors.aliyun.com';
my $mirrors = "https://$url/centos-stream";

if (@ARGV < 1) {
    die "Usage: $0 <filename1> <filename2> ...\n";
}

while (my $filename = shift @ARGV) {
    my $backup_filename = $filename . '.bak';
    rename $filename, $backup_filename;

    open my $input, "<", $backup_filename;
    open my $output, ">", $filename;

    while (<$input>) {
        s/^metalink/# metalink/;

        if (m/^name/) {
            my (undef, $repo, $arch) = split /-/;
            $repo =~ s/^\s+|\s+$//g;
            ($arch = defined $arch ? lc($arch) : '') =~ s/^\s+|\s+$//g;

            if ($repo =~ /^Extras/) {
                $_ .= "baseurl=${mirrors}/SIGs/\$releasever-stream/extras" . ($arch eq 'source' ? "/${arch}/" : "/\$basearch/") . "extras-common\n";
            } else {
                $_ .= "baseurl=${mirrors}/\$releasever-stream/$repo" . ($arch eq 'source' ? "/" : "/\$basearch/") . ($arch ne '' ? "${arch}/tree/" : "os") . "\n";
            }
        }

        print $output $_;
    }
}

rpm -q perl &> /dev/null || { echo -e "\\033[01;31m "安装perl工具,请稍等..."\033[0m";yum -y install perl ; }

perl ./update_mirror.pl /etc/yum.repos.d/centos*.repo

dnf clean all && dnf makecache

CentOS Stream 8:

MIRROR=mirrors.aliyun.com
sed -i.bak -e 's|^mirrorlist=|#mirrorlist=|g' -e 's|^#baseurl=http://mirror.centos.org/$contentdir|baseurl=https://'${MIRROR}'/centos|g' /etc/yum.repos.d/CentOS-*.repo

dnf clean all && dnf makecache

CentOS 7:

MIRROR=mirrors.aliyun.com
sed -i.bak -e 's|^mirrorlist=|#mirrorlist=|g' -e 's|^#baseurl=http://mirror.centos.org|baseurl=https://'${MIRROR}'|g' /etc/yum.repos.d/CentOS-*.repo

yum clean all && yum makecache

Ubuntu 22.04和20.04:

MIRROR=mirrors.aliyun.com
OLD_MIRROR=`sed -rn "s@^deb http(.*)://(.*)/ubuntu/? $(lsb_release -cs) main.*@\2@p" /etc/apt/sources.list`

sed -i.bak 's/'${OLD_MIRROR}'/'${MIRROR}'/g' /etc/apt/sources.list

apt update

Ubuntu 18.04:

MIRROR=mirrors.aliyun.com
OLD_MIRROR=`sed -rn "s@^deb http(.*)://(.*)/ubuntu/? $(lsb_release -cs) main.*@\2@p" /etc/apt/sources.list`

sed -i.bak 's/'${OLD_MIRROR}'/'${MIRROR}'/g' /etc/apt/sources.list

SECURITY_MIRROR=`sed -rn "s@^deb http(.*)://(.*)/ubuntu $(lsb_release -cs)-security main.*@\2@p" /etc/apt/sources.list`

sed -i.bak 's/'${SECURITY_MIRROR}'/'${MIRROR}'/g' /etc/apt/sources.list

apt update

3.1.3 关闭防火墙

# Rocky和CentOS
systemctl disable --now firewalld

# CentOS 7
systemctl disable --now NetworkManager

# Ubuntu
systemctl disable --now ufw

3.1.4 禁用SELinux

#CentOS
setenforce 0
sed -i 's#SELINUX=enforcing#SELINUX=disabled#g' /etc/selinux/config

#Ubuntu
Ubuntu没有安装SELinux,不用设置

3.1.5 设置时区

ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime
echo 'Asia/Shanghai' >/etc/timezone

#Ubuntu还要设置下面内容
cat >> /etc/default/locale <<-EOF
LC_TIME=en_DK.UTF-8
EOF

3.2 Nginx版本和安装方式

Nginx版本

  • Mainline version 主要开发版本,一般为奇数版本号,比如1.19
  • Stable version 当前最新稳定版,一般为偶数版本,如:1.20
  • Legacy versions 旧的稳定版,一般为偶数版本,如:1.18

Nginx安装可以使用yum/apt或源码安装,但是推荐使用源码编译安装

  • yum/apt的版本比较旧
  • 编译安装可以更方便自定义相关路径
  • 使用源码编译可以自定义相关功能,更方便业务的上的使用

3.3 包安装

3.3.1 CentOS 安装

3.3.1.1 查看当前系统中的 nginx 版本
[root@rocky9 ~]# dnf info nginx
Last metadata expiration check: 0:04:34 ago on Wed 31 Jan 2024 02:02:01 PM CST.
Available Packages
Name         : nginx
Epoch        : 1
Version      : 1.20.1
Release      : 14.el9_2.1
Architecture : x86_64
Size         : 36 k
Source       : nginx-1.20.1-14.el9_2.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.

# CentOS 7 需要提前配置好epel源
[root@centos7 ~]# yum -y install epel-release

[root@centos7 ~]# sed -i.bak -e 's!^metalink=!#metalink=!g' -e 's!^#baseurl=!baseurl=!g' -e 's!https\?://download\.fedoraproject\.org/pub/epel!https://mirrors.aliyun.com/epel!g' -e 's!https\?://download\.example/pub/epel!https://mirrors.aliyun.com/epel!g' /etc/yum.repos.d/epel*.repo

[root@centos7 ~]# yum info nginx
Loaded plugins: fastestmirror
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        : epel/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.
3.3.1.2 官方包源安装最新版本 nginx

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

官方包链接:

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

官方 yum 源链接

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

通过官方 yum 源安装nginx:

# 添加nginx仓库
[root@rocky9 ~]# cat > /etc/yum.repos.d/nginx.repo <<-EOF
[nginx-stable]
name=nginx stable repo
baseurl=https://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=https://nginx.org/packages/mainline/centos/\$releasever/\$basearch/
gpgcheck=1
enabled=0
gpgkey=https://nginx.org/keys/nginx_signing.key
module_hotfixes=true
EOF

# 列出所有版本
[root@rocky9 ~]# yum list nginx --showduplicates
Last metadata expiration check: 0:00:52 ago on Wed 31 Jan 2024 02:18:37 PM CST.
Available Packages
nginx.x86_64                                      1:1.20.1-14.el9_2.1                                       appstream   
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-stabl

# 查看版本信息
[root@rocky9 ~]# dnf info nginx
Last metadata expiration check: 0:01:24 ago on Wed 31 Jan 2024 02:18:37 PM CST.
Available Packages
Name         : nginx
Epoch        : 1
Version      : 1.24.0
Release      : 1.el9.ngx
Architecture : x86_64
Size         : 868 k
Source       : nginx-1.24.0-1.el9.ngx.src.rpm
Repository   : 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.

# 安装指定版本
[root@rocky9 ~]# yum -y install nginx-1.24.0
3.3.1.3 检查安装

查看nginx安装包信息

[root@rocky9 ~]# rpm -q nginx
nginx-1.24.0-1.el9.ngx.x86_64

[root@rocky9 ~]# rpm -qi nginx
Name        : nginx
Epoch       : 1
Version     : 1.24.0
Release     : 1.el9.ngx
Architecture: x86_64
Install Date: Wed 31 Jan 2024 02:21:17 PM CST
Group       : System Environment/Daemons
Size        : 3097605
License     : 2-clause BSD-like license
Signature   : RSA/SHA256, Wed 12 Apr 2023 01:47:16 AM CST, Key ID abf5bd827bd9bf62
Source RPM  : nginx-1.24.0-1.el9.ngx.src.rpm
Build Date  : Wed 12 Apr 2023 01:21:56 AM CST
Build Host  : ip-10-1-17-49.eu-central-1.compute.internal
Vendor      : NGINX Packaging <nginx-packaging@f5.com>
URL         : https://nginx.org/
Summary     : High performance web server
Description :
nginx [engine x] is an HTTP and reverse proxy server, as well as
a mail proxy server.

[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/2f
/usr/lib/.build-id/2f/1aebf1c44110efa44f0ddc88a30c3c35bec25c
/usr/lib/.build-id/42
/usr/lib/.build-id/42/201aa568b3c7e88fcc8b2734bcf8ea7899a847
/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.24.0
/usr/share/doc/nginx-1.24.0/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
}
3.3.1.4 nginx 程序用法帮助
[root@rocky9 ~]# nginx -h
nginx version: nginx/1.24.0
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 # 设置全局指令,注意和配置文件不要同时配置,否则冲突

[root@rocky9 ~]# nginx -g "worker_processes 6;"
nginx: [emerg] "worker_processes" directive is duplicate in /etc/nginx/nginx.conf:3

[root@rocky9 ~]# vim /etc/nginx/nginx.conf
#worker_processes  auto;

[root@rocky9 ~]# nginx -g "worker_processes 6;"
[root@rocky9 ~]# ps aux|grep nginx
root       11608  0.0  0.0  10420   976 ?        Ss   14:34   0:00 nginx: master process nginx -g worker_processes 6;
nginx      11609  0.0  0.2  13688  4708 ?        S    14:34   0:00 nginx: worker process
nginx      11610  0.0  0.2  13688  4708 ?        S    14:34   0:00 nginx: worker process
nginx      11611  0.0  0.2  13688  4708 ?        S    14:34   0:00 nginx: worker process
nginx      11612  0.0  0.2  13688  4708 ?        S    14:34   0:00 nginx: worker process
nginx      11613  0.0  0.2  13688  4708 ?        S    14:34   0:00 nginx: worker process
nginx      11614  0.0  0.2  13688  4708 ?        S    14:34   0:00 nginx: worker process
root       11616  0.0  0.1   6408  2176 pts/0    S+   14:34   0:00 grep --color=auto nginx

[root@rocky9 ~]# nginx -s quit
[root@rocky9 ~]# ps aux|grep nginx
root       11619  0.0  0.1   6408  2176 pts/0    S+   14:34   0:00 grep --color=auto nginx

# 前台运行
[root@rocky9 ~]# nginx -g 'daemon off;'
3.3.1.5 验证 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.24.0
built by gcc 11.2.1 20220127 (Red Hat 11.2.1-9) (GCC) 
built with OpenSSL 3.0.1 14 Dec 2021 (running 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-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'
3.3.1.6 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
3.3.1.7 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 ~]# grep -Ev "^ *#|^$" /etc/nginx/nginx.conf
user  nginx;
worker_processes  auto;
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;
    keepalive_timeout  65;
    include /etc/nginx/conf.d/*.conf;
}
3.3.1.8 启动 Nginx
[root@rocky9 ~]# systemctl enable --now nginx
Created symlink /etc/systemd/system/multi-user.target.wants/nginx.service → /usr/lib/systemd/system/nginx.service.
[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 Wed 2024-01-31 14:42:45 CST; 10s ago
       Docs: http://nginx.org/en/docs/
    Process: 11754 ExecStart=/usr/sbin/nginx -c /etc/nginx/nginx.conf (code=exited, status=0/SUCCESS)
   Main PID: 11755 (nginx)
      Tasks: 3 (limit: 10840)
     Memory: 2.9M
        CPU: 9ms
     CGroup: /system.slice/nginx.service
             ├─11755 "nginx: master process /usr/sbin/nginx -c /etc/nginx/nginx.conf"
             ├─11756 "nginx: worker process"
             └─11757 "nginx: worker process"

Jan 31 14:42:45 rocky9 systemd[1]: Starting nginx - high performance web server...
Jan 31 14:42:45 rocky9 systemd[1]: Started nginx - high performance web server.
3.3.1.9 访问 Nginx

Nginx介绍、架构和安装-LMLPHP

3.3.2 Ubuntu 安装

3.3.2.1 查看当前系统中的 nginx 版本
root@ubuntu2204:~# apt info nginx
Package: nginx
Version: 1.18.0-6ubuntu14.4
Priority: optional
Section: web
Origin: Ubuntu
Maintainer: Ubuntu Developers <ubuntu-devel-discuss@lists.ubuntu.com>
Original-Maintainer: Debian Nginx Maintainers <pkg-nginx-maintainers@alioth-lists.debian.net>
Bugs: https://bugs.launchpad.net/ubuntu/+filebug
Installed-Size: 50.2 kB
Depends: nginx-core (<< 1.18.0-6ubuntu14.4.1~) | nginx-full (<< 1.18.0-6ubuntu14.4.1~) | nginx-light (<< 1.18.0-6ubuntu14.4.1~) | nginx-extras (<< 1.18.0-6ubuntu14.4.1~), nginx-core (>= 1.18.0-6ubuntu14.4) | nginx-full (>= 1.18.0-6ubuntu14.4) | nginx-light (>= 1.18.0-6ubuntu14.4) | nginx-extras (>= 1.18.0-6ubuntu14.4)
Breaks: libnginx-mod-http-lua (<< 1.18.0-6ubuntu5)
Homepage: https://nginx.net
Download-Size: 3872 B
APT-Sources: https://mirrors.aliyun.com/ubuntu jammy-updates/main amd64 Packages
Description: small, powerful, scalable web/proxy server
 Nginx ("engine X") is a high-performance web and reverse proxy server
 created by Igor Sysoev. It can be used both as a standalone web server
 and as a proxy to reduce the load on back-end HTTP or mail servers.
 .
 This is a dependency package to install either nginx-core (by default),
 nginx-full, nginx-light or nginx-extras.

N: There are 2 additional records. Please use the '-a' switch to see them.
3.3.2.2 官方包源安装最新版本 nginx

官方 apt 源链接:

http://nginx.org/en/linux_packages.html#Ubuntu

通过官方 apt 源安装nginx:

# 安装先决条件:
root@ubuntu2204:~# apt -y install curl gnupg2 ca-certificates lsb-release ubuntu-keyring

# 导入官方的 nginx 签名密钥,以便 apt 可以验证软件包的真实性。获取密钥
root@ubuntu2204:~# curl https://nginx.org/keys/nginx_signing.key | gpg --dearmor \
    | sudo tee /usr/share/keyrings/nginx-archive-keyring.gpg >/dev/null

# 确认下载的文件包含正确的密钥:
root@ubuntu2204:~# gpg --dry-run --quiet --no-keyring --import --import-options import-show /usr/share/keyrings/nginx-archive-keyring.gpg

# 输出结果应包含完整的指纹 573BFD6B3D8FBC641079A6ABABF5BD827BD9BF62,如下所示:
pub   rsa2048 2011-08-19 [SC] [expires: 2024-06-14]
      573BFD6B3D8FBC641079A6ABABF5BD827BD9BF62
uid                      nginx signing key <signing-key@nginx.com>


# 要为稳定的 nginx 软件包设置 apt 软件仓库,请运行以下命令:
root@ubuntu2204:~# echo "deb [signed-by=/usr/share/keyrings/nginx-archive-keyring.gpg] \
http://nginx.org/packages/ubuntu `lsb_release -cs` nginx" \
    | sudo tee /etc/apt/sources.list.d/nginx.list

# 设置版本库钉选,使我们的软件包优先于发行版提供的软件包:
root@ubuntu2204:~# echo -e "Package: *\nPin: origin nginx.org\nPin: release o=nginx\nPin-Priority: 900\n" \
    | sudo tee /etc/apt/preferences.d/99nginx
Package: *
Pin: origin nginx.org
Pin: release o=nginx
Pin-Priority: 900

# 更新镜像源
root@ubuntu2204:~# apt update

# 列出所有版本
root@ubuntu2204:~# apt-cache madison nginx
     nginx | 1.24.0-1~jammy | http://nginx.org/packages/ubuntu jammy/nginx amd64 Packages
     nginx | 1.22.1-1~jammy | http://nginx.org/packages/ubuntu jammy/nginx amd64 Packages
     nginx | 1.22.0-1~jammy | http://nginx.org/packages/ubuntu jammy/nginx amd64 Packages
     nginx | 1.20.2-1~jammy | http://nginx.org/packages/ubuntu jammy/nginx amd64 Packages
     nginx | 1.18.0-6ubuntu14.4 | https://mirrors.aliyun.com/ubuntu jammy-updates/main amd64 Packages
     nginx | 1.18.0-6ubuntu14.3 | https://mirrors.aliyun.com/ubuntu jammy-security/main amd64 Packages
     nginx | 1.18.0-6ubuntu14 | https://mirrors.aliyun.com/ubuntu jammy/main amd64 Packages

# 查看版本信息
root@ubuntu2204:~# apt info nginx
Package: nginx
Version: 1.24.0-1~jammy
Priority: optional
Section: httpd
Maintainer: NGINX Packaging <nginx-packaging@f5.com>
Installed-Size: 3283 kB
Provides: httpd, nginx, nginx-r1.24.0
Depends: libc6 (>= 2.34), libcrypt1 (>= 1:4.1.0), libpcre2-8-0 (>= 10.22), libssl3 (>= 3.0.0~~alpha1), zlib1g (>= 1:1.1.4), lsb-base (>= 3.0-6), adduser
Conflicts: nginx-common, nginx-core
Replaces: nginx-common, nginx-core
Homepage: https://nginx.org
Download-Size: 1012 kB
APT-Sources: http://nginx.org/packages/ubuntu jammy/nginx amd64 Packages
Description: high performance web server
 nginx [engine x] is an HTTP and reverse proxy server, as well as
 a mail proxy server.

N: There are 6 additional records. Please use the '-a' switch to see them.

# 安装指定版本
root@ubuntu2204:~# apt -y install nginx=1.24.0-1~jammy
3.3.2.3 检查安装

查看nginx安装包信息

root@ubuntu2204:~# dpkg -s nginx
Package: nginx
Status: install ok installed
Priority: optional
Section: httpd
Installed-Size: 3206
Maintainer: NGINX Packaging <nginx-packaging@f5.com>
Architecture: amd64
Version: 1.24.0-1~jammy
Replaces: nginx-common, nginx-core
Provides: httpd, nginx, nginx-r1.24.0
Depends: libc6 (>= 2.34), libcrypt1 (>= 1:4.1.0), libpcre2-8-0 (>= 10.22), libssl3 (>= 3.0.0~~alpha1), zlib1g (>= 1:1.1.4), lsb-base (>= 3.0-6), adduser
Conflicts: nginx-common, nginx-core
Conffiles:
 /etc/default/nginx e2b1ae0f31c6d03d3305ef526b0ba3b5
 /etc/default/nginx-debug 719f6f9981039a05a64c201a4b1db19f
 /etc/init.d/nginx 7224be660d7c280a775bd6eca2547df4
 /etc/init.d/nginx-debug 57e8f64b4f464fc13701c6b22240ac10
 /etc/logrotate.d/nginx a4da44b03e39926b999329061770362b
 /etc/nginx/conf.d/default.conf 25c02145e4a2e1d2bc6da5d585cddd32
 /etc/nginx/fastcgi_params 4729c30112ca3071f4650479707993ad
 /etc/nginx/mime.types 754582375e90b09edaa6d3dbd657b3cf
 /etc/nginx/nginx.conf 756e7eaae19e95b5f49ce81e73b10512
 /etc/nginx/scgi_params df8c71e25e0356ffc539742f08fddfff
 /etc/nginx/uwsgi_params 88ac833ee8ea60904a8b3063fde791de
Description: high performance web server
 nginx [engine x] is an HTTP and reverse proxy server, as well as
 a mail proxy server.
Homepage: https://nginx.org

root@ubuntu2204:~# dpkg -L nginx
/.
/etc
/etc/default
/etc/default/nginx
/etc/default/nginx-debug
/etc/init.d
/etc/init.d/nginx
/etc/init.d/nginx-debug
/etc/logrotate.d
/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/nginx.conf
/etc/nginx/scgi_params
/etc/nginx/uwsgi_params
/lib
/lib/systemd
/lib/systemd/system
/lib/systemd/system/nginx-debug.service
/lib/systemd/system/nginx.service
/usr
/usr/lib
/usr/lib/nginx
/usr/lib/nginx/modules
/usr/sbin
/usr/sbin/nginx
/usr/sbin/nginx-debug
/usr/share
/usr/share/doc
/usr/share/doc/nginx
/usr/share/doc/nginx/CHANGES.ru.gz
/usr/share/doc/nginx/README
/usr/share/doc/nginx/changelog.Debian.gz
/usr/share/doc/nginx/changelog.gz
/usr/share/doc/nginx/copyright
/usr/share/lintian
/usr/share/lintian/overrides
/usr/share/lintian/overrides/nginx
/usr/share/man
/usr/share/man/man8
/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
/var/cache
/var/cache/nginx
/var/log
/var/log/nginx
/etc/nginx/modules

# 带有自动日志切割功能
root@ubuntu2204:~# 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
}
3.3.2.4 nginx 程序用法帮助
root@ubuntu2204:~# nginx -h
nginx version: nginx/1.24.0
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
  -p prefix     : set prefix path (default: /etc/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
3.3.2.5 验证 Nginx
root@ubuntu2204:~# nginx -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful

root@ubuntu2204:~# nginx -V
nginx version: nginx/1.24.0
built by gcc 11.2.0 (Ubuntu 11.2.0-19ubuntu1) 
built with OpenSSL 3.0.2 15 Mar 2022
TLS SNI support enabled
configure arguments: --prefix=/etc/nginx --sbin-path=/usr/sbin/nginx --modules-path=/usr/lib/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-mail --with-mail_ssl_module --with-stream --with-stream_realip_module --with-stream_ssl_module --with-stream_ssl_preread_module --with-cc-opt='-g -O2 -ffile-prefix-map=/data/builder/debuild/nginx-1.24.0/debian/debuild-base/nginx-1.24.0=. -flto=auto -ffat-lto-objects -flto=auto -ffat-lto-objects -fstack-protector-strong -Wformat -Werror=format-security -Wp,-D_FORTIFY_SOURCE=2 -fPIC' --with-ld-opt='-Wl,-Bsymbolic-functions -flto=auto -ffat-lto-objects -flto=auto -Wl,-z,relro -Wl,-z,now -Wl,--as-needed -pie'
3.3.2.6 Nginx 启动文件
root@ubuntu2204:~# cat /lib/systemd/system/nginx.service
[Unit]
Description=nginx - high performance web server
Documentation=https://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
3.3.2.7 Nginx 配置文件
root@ubuntu2204:~# tree /etc/nginx/
/etc/nginx/
├── conf.d
│   └── default.conf
├── fastcgi_params
├── mime.types
├── modules -> /usr/lib/nginx/modules
├── nginx.conf
├── scgi_params
└── uwsgi_params

2 directories, 6 files

root@ubuntu2204:~# grep -Ev "^ *#|^$" /etc/nginx/nginx.conf
user  nginx;
worker_processes  auto;
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;
    keepalive_timeout  65;
    include /etc/nginx/conf.d/*.conf;
}
3.3.2.8 启动 Nginx
root@ubuntu2204:~# systemctl enable --now nginx
Synchronizing state of nginx.service with SysV service script with /lib/systemd/systemd-sysv-install.
Executing: /lib/systemd/systemd-sysv-install enable nginx

root@ubuntu2204:~# systemctl enable --now nginx
Synchronizing state of nginx.service with SysV service script with /lib/systemd/systemd-sysv-install.
Executing: /lib/systemd/systemd-sysv-install enable nginx
root@ubuntu2204:~# systemctl status nginx
● nginx.service - nginx - high performance web server
     Loaded: loaded (/lib/systemd/system/nginx.service; enabled; vendor preset: enabled)
     Active: active (running) since Wed 2024-01-31 16:17:07 CST; 20s ago
       Docs: https://nginx.org/en/docs/
    Process: 32443 ExecStart=/usr/sbin/nginx -c /etc/nginx/nginx.conf (code=exited, status=0/SUCCESS)
   Main PID: 32444 (nginx)
      Tasks: 3 (limit: 2178)
     Memory: 2.6M
        CPU: 7ms
     CGroup: /system.slice/nginx.service
             ├─32444 "nginx: master process /usr/sbin/nginx -c /etc/nginx/nginx.conf"
             ├─32445 "nginx: worker process" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" ""
             └─32446 "nginx: worker process" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" ""

Jan 31 16:17:07 ubuntu2204 systemd[1]: Starting nginx - high performance web server...
Jan 31 16:17:07 ubuntu2204 systemd[1]: Started nginx - high performance web server.
3.3.2.9 访问 Nginx

Nginx介绍、架构和安装-LMLPHP

3.4 Nginx 编译安装

编译器介绍:

源码安装需要提前准备标准的编译器,GCC的全称是(GNU Compiler collection),其有GNU开发,并以GPL即LGPL许可,是自由的类UNIX即苹果电脑Mac OS X操作系统的标准编译器,因为GCC原本只能处理C语言,所以原名为GNU C语言编译器,后来得到快速发展,可以处理C++,Fortran,pascal,objective-C,java以及Ada等其他语言,此外还需要Automake工具,以完成自动创建Makefile的工作,Nginx的一些模块需要依赖第三方库,比如: pcre(支持rewrite),zlib(支持gzip模块)和openssl(支持ssl模块)等。

3.4.1 编译安装 Nginx

官方源码包下载地址:

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

编译安装:

# Rocky和CentOS
yum -y install make gcc pcre-devel openssl-devel zlib-devel

# Ubuntu
apt update
apt -y install make gcc libpcre3 libpcre3-dev openssl libssl-dev zlib1g-dev 

[root@rocky9 ~]# useradd -s /sbin/nologin -r nginx

[root@rocky9 ~]# cd /usr/local/src/

[root@rocky9 src]# wget https://nginx.org/download/nginx-1.24.0.tar.gz
-bash: wget: command not found
[root@rocky9 src]# dnf -y install wget

[root@rocky9 src]# wget https://nginx.org/download/nginx-1.24.0.tar.gz

[root@rocky9 src]# tar xf nginx-1.24.0.tar.gz

[root@rocky9 src]# cd nginx-1.24.0
[root@rocky9 nginx-1.24.0]# ./configure --prefix=/apps/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.24.0]# make -j 2 && make install

# 修改权限
[root@rocky9 nginx-1.24.0]# chown -R nginx.nginx /apps/nginx

nginx完成安装以后,有四个主要的目录

[root@rocky9 nginx-1.24.0]# ll /apps/nginx
total 4
drwxr-xr-x 2 nginx nginx 4096 Jan 31 16:47 conf
drwxr-xr-x 2 nginx nginx   40 Jan 31 16:47 html
drwxr-xr-x 2 nginx nginx    6 Jan 31 16:47 logs
drwxr-xr-x 2 nginx nginx   19 Jan 31 16:47 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二进制启动脚本,可以接受不同的参数以实现不同的功能。

3.4.2 验证版本及编译参数

[root@rocky9 nginx-1.24.0]# echo "PATH=${NGINX_INSTALL_DIR}/sbin:${PATH}" > /etc/profile.d/nginx.sh
[root@rocky9 nginx-1.24.0]# exit

# 查看版本
[root@rocky9 ~]# nginx -v
nginx version: nginx/1.24.0

# 查看编译参数
[root@rocky9 ~]# nginx -V
nginx version: nginx/1.24.0
built by gcc 11.4.1 20230605 (Red Hat 11.4.1-2) (GCC) 
built with OpenSSL 3.0.7 1 Nov 2022
TLS SNI support enabled
configure arguments: --prefix=/apps/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

3.4.3 启动和停止 nginx 测试访问 web 界面

#启动nginx
[root@rocky9 ~]# nginx

浏览器可以访问看到下面图示

Nginx介绍、架构和安装-LMLPHP

[root@rocky9 ~]# ss -ntl
State         Recv-Q        Send-Q               Local Address:Port               Peer Address:Port       Process       
LISTEN        0             511                        0.0.0.0:80                      0.0.0.0:*                        
LISTEN        0             128                        0.0.0.0:22                      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                         [::]:*

3.4.4 创建 Nginx 自启动文件

[root@rocky9 ~]# cat > /lib/systemd/system/nginx.service <<EOF
[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=/apps/nginx/logs/nginx.pid
ExecStart=/apps/nginx/sbin/nginx -c /apps/nginx/conf/nginx.conf
ExecReload=/bin/kill -s HUP \$MAINPID
ExecStop=/bin/kill -s TERM \$MAINPID
LimitNOFILE=100000

[Install]
WantedBy=multi-user.target
EOF

3.4.5 验证 Nginx 自启动文件

[root@rocky9 ~]# systemctl daemon-reload
[root@rocky9 ~]# systemctl enable --now nginx

[root@rocky9 ~]# ll /apps/nginx/logs/nginx.pid 
-rw-r--r-- 1 root root 6 Jan 31 16:58 /apps/nginx/logs/nginx.pid

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

3.4.6 一键编译安装Nginx脚本

Shell脚本源码地址:

Gitee:https://gitee.com/raymond9/shell

Github:https://github.com/raymond999999/shell

可以去上面的Gitee或Github代码仓库拉取脚本。

[root@rocky9 ~]# cat install_nginx.sh 
#!/bin/bash
#
#************************************************************************************************************
#Author:        Raymond
#QQ:            88563128
#Date:          2024-01-31
#FileName:      install_nginx.sh
#URL:           raymond.blog.csdn.net
#Description:   install_haproxy for CentOS 7 & CentOS Stream 8/9 & Ubuntu 18.04/20.04/22.04 & Rocky 8/9
#Copyright (C): 2024 All rights reserved
#************************************************************************************************************
SRC_DIR=/usr/local/src
COLOR="echo -e \\033[01;31m"
END='\033[0m'

NGINX_URL=https://nginx.org/download/
NGINX_FILE=nginx-1.24.0.tar.gz
NGINX_INSTALL_DIR=/apps/nginx
CPUS=`lscpu |awk '/^CPU\(s\)/{print $2}'`

os(){
    OS_ID=`sed -rn '/^NAME=/s@.*="([[:alpha:]]+).*"$@\1@p' /etc/os-release`
}

check_file (){
    cd ${SRC_DIR}
    if [ ${OS_ID} == "CentOS" -o ${OS_ID} == "Rocky" ] &> /dev/null;then
        rpm -q wget &> /dev/null || { ${COLOR}"安装wget工具,请稍等..."${END};yum -y install wget &> /dev/null; }
    fi
    if [ ! -e ${NGINX_FILE} ];then
        ${COLOR}"缺少${NGINX_FILE}文件"${END}
        ${COLOR}'开始下载Nginx源码包'${END}
        wget ${NGINX_URL}${NGINX_FILE} || { ${COLOR}"Nginx源码包下载失败"${END}; exit; }
    else
        ${COLOR}"${NGINX_FILE}文件已准备好"${END}       
    fi
} 

install_nginx(){
    [ -d ${NGINX_INSTALL_DIR} ] && { ${COLOR}"Nginx已存在,安装失败"${END};exit; }
    ${COLOR}"开始安装Nginx"${END}
    ${COLOR}"开始安装Nginx依赖包,请稍等..."${END}
    if [ ${OS_ID} == "CentOS" -o ${OS_ID} == "Rocky" ] &> /dev/null;then
        yum -y install make gcc pcre-devel openssl-devel zlib-devel &> /dev/null
    else
        apt update &> /dev/null;apt -y install make gcc libpcre3 libpcre3-dev openssl libssl-dev zlib1g-dev &> /dev/null
    fi
    id nginx  &> /dev/null || { useradd -s /sbin/nologin -r nginx; ${COLOR}"创建Nginx用户"${END}; }
    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编译安装成功"${END} ||  { ${COLOR}"Nginx编译安装失败,退出!"${END};exit; }
    chown -R nginx.nginx /apps/nginx
    echo "PATH=${NGINX_INSTALL_DIR}/sbin:${PATH}" > /etc/profile.d/nginx.sh
    cat > /lib/systemd/system/nginx.service <<EOF
[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=${NGINX_INSTALL_DIR}/logs/nginx.pid
ExecStart=${NGINX_INSTALL_DIR}/sbin/nginx -c ${NGINX_INSTALL_DIR}/conf/nginx.conf
ExecReload=/bin/kill -s HUP \$MAINPID
ExecStop=/bin/kill -s TERM \$MAINPID
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 启动失败,退出!"${END} ; exit; }
    ${COLOR}"Nginx安装完成"${END}
}

main(){
    os
    check_file
    install_nginx
}

main
03-16 02:13