Nginx 配置文件讲解

在CentOS上部署Nginx

yum install -y nginx 
点击查看安装全过程
[root@CentOS7 ~]# yum install nginx -y
Loaded plugins: fastestmirror, langpacks
Repository epel is listed more than once in the configuration
Repository epel-debuginfo is listed more than once in the configuration
Repository epel-source is listed more than once in the configuration
Loading mirror speeds from cached hostfile
 * base: mirrors.aliyun.com
 * extras: mirrors.aliyun.com
 * updates: mirrors.aliyun.com
Resolving Dependencies
--> Running transaction check
---> Package nginx.x86_64 1:1.20.1-10.el7 will be installed
--> Processing Dependency: nginx-filesystem = 1:1.20.1-10.el7 for package: 1:nginx-1.20.1-10.el7.x86_64
--> Processing Dependency: libcrypto.so.1.1(OPENSSL_1_1_0)(64bit) for package: 1:nginx-1.20.1-10.el7.x86_64
--> Processing Dependency: libssl.so.1.1(OPENSSL_1_1_0)(64bit) for package: 1:nginx-1.20.1-10.el7.x86_64
--> Processing Dependency: libssl.so.1.1(OPENSSL_1_1_1)(64bit) for package: 1:nginx-1.20.1-10.el7.x86_64
--> Processing Dependency: nginx-filesystem for package: 1:nginx-1.20.1-10.el7.x86_64
--> Processing Dependency: libcrypto.so.1.1()(64bit) for package: 1:nginx-1.20.1-10.el7.x86_64
--> Processing Dependency: libprofiler.so.0()(64bit) for package: 1:nginx-1.20.1-10.el7.x86_64
--> Processing Dependency: libssl.so.1.1()(64bit) for package: 1:nginx-1.20.1-10.el7.x86_64
--> Running transaction check
---> Package gperftools-libs.x86_64 0:2.6.1-1.el7 will be installed
---> Package nginx-filesystem.noarch 1:1.20.1-10.el7 will be installed
---> Package openssl11-libs.x86_64 1:1.1.1k-7.el7 will be installed
--> Finished Dependency Resolution

Dependencies Resolved

===========================================================================================================================================================================================
 Package                                           Arch                                    Version                                             Repository                             Size
===========================================================================================================================================================================================
Installing:
 nginx                                             x86_64                                  1:1.20.1-10.el7                                     epel                                  588 k
Installing for dependencies:
 gperftools-libs                                   x86_64                                  2.6.1-1.el7                                         base                                  272 k
 nginx-filesystem                                  noarch                                  1:1.20.1-10.el7                                     epel                                   24 k
 openssl11-libs                                    x86_64                                  1:1.1.1k-7.el7                                      epel                                  1.5 M

Transaction Summary
===========================================================================================================================================================================================
Install  1 Package (+3 Dependent packages)

Total download size: 2.3 M
Installed size: 6.6 M
Downloading packages:
(1/4): nginx-filesystem-1.20.1-10.el7.noarch.rpm                                                                                                                    |  24 kB  00:00:00
(2/4): gperftools-libs-2.6.1-1.el7.x86_64.rpm                                                                                                                       | 272 kB  00:00:01
(3/4): nginx-1.20.1-10.el7.x86_64.rpm                                                                                                                               | 588 kB  00:00:02
(4/4): openssl11-libs-1.1.1k-7.el7.x86_64.rpm                                                                                                                       | 1.5 MB  00:00:04
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Total                                                                                                                                                      463 kB/s | 2.3 MB  00:00:05
Running transaction check
Running transaction test
Transaction test succeeded
Running transaction
  Installing : 1:openssl11-libs-1.1.1k-7.el7.x86_64                                                                                                                                    1/4
  Installing : 1:nginx-filesystem-1.20.1-10.el7.noarch                                                                                                                                 2/4
  Installing : gperftools-libs-2.6.1-1.el7.x86_64                                                                                                                                      3/4
  Installing : 1:nginx-1.20.1-10.el7.x86_64                                                                                                                                            4/4
  Verifying  : gperftools-libs-2.6.1-1.el7.x86_64                                                                                                                                      1/4
  Verifying  : 1:nginx-filesystem-1.20.1-10.el7.noarch                                                                                                                                 2/4
  Verifying  : 1:nginx-1.20.1-10.el7.x86_64                                                                                                                                            3/4
  Verifying  : 1:openssl11-libs-1.1.1k-7.el7.x86_64                                                                                                                                    4/4

Installed:
  nginx.x86_64 1:1.20.1-10.el7

Dependency Installed:
  gperftools-libs.x86_64 0:2.6.1-1.el7                         nginx-filesystem.noarch 1:1.20.1-10.el7                         openssl11-libs.x86_64 1:1.1.1k-7.el7

Complete!
[root@CentOS7 ~]#

启动Nginx

systemctl start nginx

查看Nginx进程启动状态(显示有几个worker process就是几核CPU,我这里是8核CPU)

ps -ef | grep nginx

开机自启动Nginx

systemctl enable nginx
点击查看执行过程
 [root@CentOS7 ~]# systemctl start nginx
[root@CentOS7 ~]# ps -ef | grep nginx
root      1893     1  0 13:52 ?        00:00:00 nginx: master process /usr/sbin/nginx
nginx     1894  1893  0 13:52 ?        00:00:00 nginx: worker process
nginx     1895  1893  0 13:52 ?        00:00:00 nginx: worker process
nginx     1896  1893  0 13:52 ?        00:00:00 nginx: worker process
nginx     1897  1893  0 13:52 ?        00:00:00 nginx: worker process
nginx     1898  1893  0 13:52 ?        00:00:00 nginx: worker process
nginx     1899  1893  0 13:52 ?        00:00:00 nginx: worker process
nginx     1900  1893  0 13:52 ?        00:00:00 nginx: worker process
nginx     1901  1893  0 13:52 ?        00:00:00 nginx: worker process
root      1903  1716  0 13:52 pts/0    00:00:00 grep --color=auto nginx
[root@CentOS7 ~]# systemctl enable nginx
Created symlink from /etc/systemd/system/multi-user.target.wants/nginx.service to /usr/lib/systemd/system/nginx.service.
[root@CentOS7 ~]#

yum 安装的Nginx 默认会被systemctl接管,原因是配置了启动脚本

启动脚本的位置

  • 在 CentOS 7 中,Nginx 的启动脚本通常位于 /usr/lib/systemd/system/nginx.service,你可以使用cat /usr/lib/systemd/system/nginx.service查看内容。
双击查看 nginx.service 的配置信息
[Unit]
Description=The nginx HTTP and reverse proxy server
After=network-online.target remote-fs.target nss-lookup.target
Wants=network-online.target

[Service]
Type=forking
PIDFile=/run/nginx.pid
# Nginx will fail to start if /run/nginx.pid already exists but has the wrong
# SELinux context. This might happen when running `nginx -t` from the cmdline.
# https://bugzilla.redhat.com/show_bug.cgi?id=1268621
ExecStartPre=/usr/bin/rm -f /run/nginx.pid
ExecStartPre=/usr/sbin/nginx -t
ExecStart=/usr/sbin/nginx
ExecReload=/usr/sbin/nginx -s reload
KillSignal=SIGQUIT
TimeoutStopSec=5
KillMode=process
PrivateTmp=true

[Install]
WantedBy=multi-user.target

重新加载 systemd 配置

  • 如果您修改了启动脚本,请重新加载 systemd 配置以应用更改。
systemctl daemon-reload

检查服务配置

  • 检查 Nginx 服务配置是否正确。
systemctl check nginx

启动/重启 Nginx 服务

  • 启动/重启/关闭 Nginx 服务以应用更改。
systemctl start nginx
systemctl restart nginx
systemctl stop nginx

检查 Nginx 版本和编译参数

nginx -V

 

 

 查看TCP和UDP的监听端口

netstat -lntup

netstat -lntup 是一个用于显示网络连接状态的命令行工具,通常用于诊断网络问题和查看系统上运行的服务。下面是这个命令各部分的详细解释:

  • netstat: 这是命令本身,用来显示网络连接、路由表和其他网络相关信息。
  • -l: 显示所有监听中的套接字(sockets),即展示所有正在监听的网络服务。
  • -n: 显示数字形式的地址和端口,而不是尝试查找名称(如域名)。
  • -t: 显示 TCP 协议的连接。
  • -u: 显示 UDP 协议的连接。
  • -p: 显示每个连接对应的程序名或者进程ID(PID)。

当你运行 netstat -lntup 时,它会输出一个列表,其中包括以下信息:

  • Proto: 连接的协议类型(TCP 或 UDP)。
  • Recv-Q: 接收队列的长度,通常为0,除非有数据未被应用程序读取。
  • Send-Q: 发送队列的长度,通常为0,除非有数据正等待发送。
  • Local Address: 本地地址和端口。
  • Foreign Address: 远程地址和端口,如果是监听状态则可能显示为 *:*
  • State: 连接的状态(例如,LISTENESTABLISHEDTIME_WAIT 等)。
  • PID/Program name: 对应的进程ID和程序名。
[root@CentOS7 ~]# netstat -lntup
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address           Foreign Address         State       PID/Program name
tcp        0      0 0.0.0.0:111             0.0.0.0:*               LISTEN      854/rpcbind
tcp        0      0 0.0.0.0:80              0.0.0.0:*               LISTEN      1893/nginx: master
tcp        0      0 0.0.0.0:22              0.0.0.0:*               LISTEN      1253/sshd
tcp6       0      0 :::111                  :::*                    LISTEN      854/rpcbind
tcp6       0      0 :::80                   :::*                    LISTEN      1893/nginx: master
tcp6       0      0 :::22                   :::*                    LISTEN      1253/sshd
udp        0      0 0.0.0.0:600             0.0.0.0:*                           854/rpcbind
udp        0      0 0.0.0.0:111             0.0.0.0:*                           854/rpcbind
udp6       0      0 :::600                  :::*                                854/rpcbind
udp6       0      0 :::111                  :::*                                854/rpcbind
[root@CentOS7 ~]#

想要时监控网络连接状态,您可以直接在 watch 命令后面加上 netstat -tulpnwatch 命令默认每两秒刷新一次屏幕上的输出,这可以帮助您实时观察网络连接的变化。

以下是具体的命令:

watch -n 2 'netstat -lntup'

我们可以看到,Nginx 正确地在监听 80 端口(TCP 和 TCP6)

放行 firewall 的http端口  可以参考: Centos7——防火墙(Firewall)命令 - Magiclala - 博客园 (cnblogs.com)

sudo firewall-cmd --permanent --add-service=http
sudo firewall-cmd --reload

这条命令会打开 HTTP 服务所使用的标准端口,即 TCP 80 端口。这意味着它只针对标准的 HTTP 服务端口进行配置。如果您更改了 Nginx 的启动端口为 8080,那么这条命令将不再适用于您的情况,因为 8080 端口不是 HTTP 服务的标准端口。

因此你可以使用下面的命令放行指定端口:如 80

sudo firewall-cmd --permanent --add-port=80/tcp
sudo firewall-cmd --reload

检查防火墙的状态以确认 80 端口是否已经开放。

sudo firewall-cmd --list-all
或
sudo firewall-cmd --permanent --list-port

 

点击查看全执行过程
[root@CentOS7 ~]# firewall-cmd --list-all
public (active)
  target: default
  icmp-block-inversion: no
  interfaces: ens192
  sources:
  services: dhcpv6-client ssh
  ports:
  protocols:
  masquerade: no
  forward-ports:
  source-ports:
  icmp-blocks:
  rich rules:

[root@CentOS7 ~]# firewall-cmd --permanent --list-port
80/tcp
[root@CentOS7 ~]#

这时,访问这台服务器的web业务IP地址,即可看到Nginx的默认欢迎页面:

Nginx的默认配置文件路径: /etc/nginx/nginx.conf

[root@CentOS7 nginx]# cd /etc/nginx/
[root@CentOS7 nginx]# ls
conf.d     fastcgi.conf          fastcgi_params          koi-utf  mime.types          nginx.conf          scgi_params          uwsgi_params          win-utf
default.d  fastcgi.conf.default  fastcgi_params.default  koi-win  mime.types.default  nginx.conf.default  scgi_params.default  uwsgi_params.default
[root@CentOS7 nginx]#

这里的所有.default都是官方给出的最基础的配置文件(这里不完全等于初始的配置文件,也就是说 nginx.conf ≠ nginx.conf.default),以便随时复配置。排查问题。

nginx.conf.default 内的配置内容如下:(这基本上算最小化的配置文件了)

点击查看 nginx.conf.default 配置
# 全局配置块
worker_processes  1;  # 设置工作进程的数量,这里设置为 1

# Events 块:配置事件处理机制
events {
    worker_connections  1024;  # 每个工作进程可以处理的最大并发连接数
}

# HTTP 块:HTTP 相关的配置
http {
    include       mime.types;  # 包含 MIME 类型文件
    default_type  application/octet-stream;  # 设置默认的 MIME 类型

    sendfile        on;  # 启用高效的文件传输方式
    keepalive_timeout  65;  # 设置客户端连接的超时时间

    # Server 块:定义一个或多个虚拟服务器
    server {
        listen       80;  # 监听标准 HTTP 端口 80
        server_name  localhost;  # 设置服务器名称,这里的 "localhost" 用于匹配 localhost 请求

        location / {  # 定义根目录的处理规则
            root   html;  # 设置网站根目录
            index  index.html index.htm;  # 设置索引文件列表,用于自动索引
        }

        error_page   500 502 503 504  /50x.html;  # 设置服务器错误页面
        location = /50x.html {  # 定义服务器错误页面的具体位置
            root   html;  # 设置网站根目录
        }
    }
}

nginx.conf 是 Nginx 的主配置文件,内容如下: 用grep -Ev '#|^$' nginx.conf去掉注释和换行,查看生效部分的配置文件

[root@CentOS7 nginx]# grep -Ev '#|^$' nginx.conf

# 全局配置块
user nginx;  # 设置 Nginx 启动进程运行的 用户和组
worker_processes auto;  # 自动根据服务器的 CPU 核心数设置工作进程的数量
error_log /var/log/nginx/error.log;  # 设置错误日志文件的位置
pid /run/nginx.pid;  # 设置主进程 PID 文件的位置
include /usr/share/nginx/modules/*.conf;  # 包含模块配置文件

# Events 块:配置事件处理机制
events {
    worker_connections 1024;  # 每个工作进程可以处理的最大并发连接数
}

# HTTP 块:HTTP 相关的配置
http {
    # 日志格式定义
    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;  # 减少 HTTP 响应中的 TCP 分段数量
    tcp_nodelay         on;  # 禁用 Nagle 算法,减少延迟
    keepalive_timeout   65;  # 设置客户端连接的超时时间
    types_hash_max_size 4096;  # 设置 MIME 类型哈希表的最大大小

    # MIME 类型相关设置
    include             /etc/nginx/mime.types;  # 包含 MIME 类型文件
    default_type        application/octet-stream;  # 设置默认的 MIME 类型

    # 包含其他配置文件
    include /etc/nginx/conf.d/*.conf;

    # Server 块:定义一个或多个虚拟服务器
    server {
        # 监听端口
        listen       80;  # 监听标准 HTTP 端口 80
        listen       [::]:80;  # 监听 IPv6 地址的 HTTP 端口 80

        # 服务器名称
        server_name  _;  # 设置服务器名称,这里的 "_" 表示匹配任何请求

        # 网站根目录
        root         /usr/share/nginx/html;  # 设置网站根目录

        # 包含额外的默认配置文件
        include /etc/nginx/default.d/*.conf;

        # 错误页面
        error_page 404 /404.html;  # 设置 404 错误页面
        location = /404.html { }  # 定义 404 错误页面的具体位置

        error_page 500 502 503 504 /50x.html;  # 设置服务器错误页面
        location = /50x.html { }  # 定义服务器错误页面的具体位置
    }
}

原始配置文件代码 全解读:

点击查看 nginx.conf 全部配置内容
# For more information on configuration, see:
#   * Official English Documentation: http://nginx.org/en/docs/
#   * Official Russian Documentation: http://nginx.org/ru/docs/

# 全局配置块
user nginx;  # 设置 Nginx 进程运行的用户和组
worker_processes auto;  # 根据服务器的 CPU 核心数自动设置工作进程的数量
error_log /var/log/nginx/error.log;  # 设置错误日志文件的位置
pid /run/nginx.pid;  # 设置主进程 PID 文件的位置

# Load dynamic modules. See /usr/share/doc/nginx/README.dynamic.
include /usr/share/nginx/modules/*.conf;  # 包含动态模块配置文件

# Events 块:配置事件处理机制
events {
    worker_connections 1024;  # 每个工作进程可以处理的最大并发连接数
}

# HTTP 块:HTTP 相关的配置
http {
    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;  # 减少 HTTP 响应中的 TCP 分段数量
    tcp_nodelay         on;  # 禁用 Nagle 算法,减少延迟
    keepalive_timeout   65;  # 设置客户端连接的超时时间
    types_hash_max_size 4096;  # 设置 MIME 类型哈希表的最大大小

    include             /etc/nginx/mime.types;  # 包含 MIME 类型文件
    default_type        application/octet-stream;  # 设置默认的 MIME 类型

    # Load modular configuration files from the /etc/nginx/conf.d directory.
    # See http://nginx.org/en/docs/ngx_core_module.html#include
    # for more information.
    include /etc/nginx/conf.d/*.conf;  # 包含其他配置文件
    
    # Server 块(在http内配置):定义一个或多个虚拟服务器
    server {
        listen       80;  # 监听标准 HTTP 端口 80
        listen       [::]:80;  # 监听 IPv6 地址的 HTTP 端口 80
        server_name  _;  # 设置服务器名称,这里的 "_" 表示匹配任何请求
        root         /usr/share/nginx/html;  # 设置网站根目录

        # Load configuration files for the default server block.
        include /etc/nginx/default.d/*.conf;  # 包含默认服务器块的额外配置文件

        error_page 404 /404.html;  # 设置 404 错误页面
        location = /404.html { }  # 定义 404 错误页面的具体位置

        error_page 500 502 503 504 /50x.html;  # 设置服务器错误页面
        location = /50x.html { }  # 定义服务器错误页面的具体位置
    }

# Settings for a TLS enabled server.
#    # 如果要启用https证书加密的话配置如下:
#    # Server 块(在http内配置):定义一个或多个虚拟服务器
#    server {
#        listen       443 ssl http2;  # 监听 HTTPS 端口 443
#        listen       [::]:443 ssl http2;  # 监听 IPv6 地址的 HTTPS 端口 443
#        server_name  _;  # 设置服务器名称
#        root         /usr/share/nginx/html;  # 设置网站根目录
#
#        ssl_certificate "/etc/pki/nginx/server.crt";  # 设置 SSL 证书文件路径
#        ssl_certificate_key "/etc/pki/nginx/private/server.key";  # 设置 SSL 私钥文件路径
#        ssl_session_cache shared:SSL:1m;  # 设置 SSL 会话缓存
#        ssl_session_timeout  10m;  # 设置 SSL 会话超时时间
#        ssl_ciphers HIGH:!aNULL:!MD5;  # 设置 SSL 密码
#        ssl_prefer_server_ciphers on;  # 优先使用服务器密码
#
#        # Load configuration files for the default server block.
#        include /etc/nginx/default.d/*.conf;  # 包含默认服务器块的额外配置文件
#
#        error_page 404 /404.html;  # 设置 404 错误页面
#            location = /40x.html { }  # 定义 404 错误页面的具体位置
#
#        error_page 500 502 503 504 /50x.html;  # 设置服务器错误页面
#            location = /50x.html { }  # 定义服务器错误页面的具体位置
#    }
}

 

posted @ 2024-08-20 14:27  Magiclala  阅读(4)  评论(0编辑  收藏  举报