麒麟操作系统服务架构保姆级教程(五)NGINX中间件详解

++如果你想拥有你从未拥有过的东西,那么你必须去做你从未做过的事情++

上次小屁用二进制的方式部署完NGINX之后,一直想写个使用systemctl用来管理nginx脚本,用来简单的启动或关闭nginx服务,周六周日写了两天,无一例外,失败了,但是我无意间发现了一个比较简单的管理nginx的方法,安装完nginx之后的配置文件的文件和yum安装的配置文件大概类似,和我之前yum安装nginx的玩法类似,拿过来给大家参考下,好了言归正传,直接开干

目录

一、Nginx编译安装

​编辑

nginx帮助信息

二、Nginx配置文件解析

1.ngnix区块关系

2、密码验证

3、IP地址限制

4、Nginx状态模块

5、连接限制,请求限制

6、loaction匹配规则

location匹配规则优先级

💬欢迎交流:在学习过程中如果你有任何疑问或想法,欢迎在评论区留言,我们可以共同探讨学习的内容。你的支持是我持续创作的动力!

👍点赞、收藏与推荐:如果你觉得这篇文章对你有所帮助,请不要忘记点赞、收藏,并分享给更多的小伙伴!你们的鼓励是我不断进步的源泉!

🚀推广给更多人:如果你认为这篇文章对你有帮助,欢迎分享给更多对Linux感兴趣的朋友,让我们一起进步,共同提升!

一、Nginx编译安装

bash 复制代码
想要实现一个功能,但是Nginx默认没有此模块,需要编译安装的方式将新的模块编译进已安装的Nginx服务中
nginx_upstream_check
检查Nginx默认模块:
[root@web01 conf.d]#nginx -V    之前我二进制安装的nginx查看版本信息和安装了哪些插件
nginx version: nginx/1.26.2
built by gcc 7.3.0 (GCC) 
built with OpenSSL 1.1.1f  31 Mar 2020
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 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector-strong --param=ssp-buffer-size=4 -grecord-gcc-switches -m64 -mtune=generic -fPIC' --with-ld-opt='-Wl,-z,relro -Wl,-z,now -pie'
第一步:安装依赖
[root@web01 ~]#yum install -y gcc glibc gcc-c++ pcre-devel openssl-devel patch
第二步: 下载和已经安装的Nginx版本相同的源码
[root@web01 ~]#nginx -v
nginx version: nginx/1.26.2
[root@web01 ~]#wget http://nginx.org/download/nginx-1.26.2.tar.gz
下面我会多下载一个插件,这个插件主要的功能是对 Nginx 的上游服务器(upstream servers)进行健康检查,这在构建高可用的反向代理或负载均衡架构时非常重要(多这一个服务后面会用到,主要我看的安装文档里内置的,我也没有删除,后续做反向代理和负载均衡会用到)
下载第三方插件模块:
先下载windows
github.com/yaoweibin/nginx_upstream_check_module/archive/master.zip
然后再上传到lb01
解压nginx
 [root@web01 ~]#tar xf nginx-1.26.2.tar.gz
解压插件:
 [root@web01 ~]#unzip nginx_upstream_check_module-master.zip
第三步: 将下载的模块加载到nginx模块中
[root@web01 nginx-1.26.2]#patch -p1 < ../nginx_upstream_check_module-master/check_1.20.1+.patch
将模块目录配置到nginx中
[root@web01 conf.d]#./configure --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 --add-module=/root/nginx_upstream_check_module-master --with-cc-opt='-O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector-strong --param=ssp-buffer-size=4 -grecord-gcc-switches -m64 -mtune=generic -fPIC' --with-ld-opt='-Wl,-z,relro -Wl,-z,now -pie'
第四步: make编译
[root@web01 nginx-1.26.2]#make
第五步: 编译安装
[root@web01 nginx-1.26.2]#make install
​
安装完成之后测试启动测试
[root@web01 conf.d]#nginx
记得关闭防火墙(2道哦~~~~)
[root@web01 local]#systemctl stop iptables.service 
[root@web01 local]#systemctl stop firewalld.service 
[root@web01 local]#systemctl disable firewalld.service
[root@web01 local]#systemctl disable iptables.service 
​
当然了,小屁又学了一招
直接开放防火墙的80端口访问
firewall-cmd --add-service=http --permanent          #开放服务器HTTP协议的端口默认80
firewall-cmd --add-port=80/tcp --permanent          #开放80端口nginx默认端口,Tomcat默认8080,https默认443
​
iptables -A INPUT -p tcp --dport 80 -j ACCEPT  

nginx帮助信息

bash 复制代码
查看帮助信息
[root@web01 nginx]#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                                                         #1
  -v            : show version and exit                                             #2
  -V            : show version and configure options then exit                      
  -t            : test configuration and exit                                       #3
  -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       #4
  -p prefix     : set prefix path (default: /etc/nginx/)                            #5
  -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                   
​
​
#1:-? 或 -h
作用:用于查看 nginx 命令的帮助信息,也就是你执行 nginx -help 所展示出来的这些内容,能帮助你了解 nginx 命令有哪些可用参数以及它们各自的功能,方便后续正确操作 nginx 服务。
​
​
#2查看版本信息
参数:-v 和 -V
作用:
-v 参数可以简单地显示 nginx 的版本号,然后直接退出
-V 参数则更为详细,除了显示版本号之外,还会展示 nginx 的配置选项相关信息,比如编译时启用了哪些模块等内容,在排查与版本及编译配置相关问题时比较有用。
​
​
#3测试配置文件
参数:-t 和 -T
作用:
-t 参数用于测试 nginx 的配置文件语法是否正确以及配置逻辑等是否合理,执行后如果配置没问题会显示相应提示然后退出,如果有错误则会指出具体的错误位置和类型,这是在修改配置文件后经常要做的操作,确保配置文件能被 nginx 正常应用。例如,执行 nginx -t 命令来测试默认配置文件(通常是 /etc/nginx/nginx.conf )的情况。
-T 参数在测试配置文件的基础上,还会将完整的配置内容输出(也就是把配置文件里的所有信息都打印出来),便于你进一步详细查看配置的细节,当需要确认配置文件具体内容或者排查一些因配置内容不明导致的问题时可以使用这个参数。
​
-q 的主要作用是在进行配置文件测试(使用 -t 参数来测试配置文件时)时,抑制非错误消息的输出。通常情况下,当你执行 nginx -t 命令去测试 nginx 配置文件语法是否正确以及配置逻辑等是否合理时,nginx 会输出比较详细的信息,告知你配置文件测试的结果情况。
而如果添加了 -q 参数,也就是执行 nginx -q -t 命令(-q 和 -t 可以按这样顺序连着使用)时,在配置文件测试通过的情况下,它不会输出这些常规的提示信息,只有当配置文件存在错误时,才会显示相应的错误提示信息,比如指出语法错误在配置文件的具体什么位置等错误相关内容,使用 -q 参数可以让输出更加简洁,便于你快速判断配置文件是否存在问题,而不用在大量正常提示信息中去查找有没有错误提示了。
​
​
#4发送信号给主进程
参数:-s signal
作用:
通过这个参数可以向 nginx 的主进程发送不同的信号,以实现不同的操作,常见的信号及对应的操作如下:
stop:用于立即停止 nginx 服务,执行 nginx -s stop 命令后,nginx 服务会马上终止运行,所有连接都会断开。
quit:相对 stop 来说,quit 信号是一种 "优雅" 停止的方式,nginx 主进程会先处理完当前正在进行的请求,然后再关闭服务,执行 nginx -s quit 命令可实现这种平缓关闭服务的效果。
reopen:当你想让 nginx 重新打开日志文件(比如进行日志文件的轮转等操作后),可以执行 nginx -s reopen 命令,这样 nginx 会重新打开相关的日志文件进行记录。
reload:这个信号最为常用,在修改了 nginx 的配置文件后,为了让新配置生效,执行 nginx -s reload 命令,nginx 主进程会重新读取配置文件并应用新配置,而且服务不会中断,能继续正常处理请求,保障业务的连续性。
​
​
#5设置相关路径和文件
参数:-p prefix、-e filename、-c filename、-g directives
作用:
-p prefix:用于指定 nginx 的安装前缀路径,默认是 /etc/nginx/,不过在某些特殊场景下,比如你将 nginx 安装到了其他自定义的目录下,想让 nginx 命令能基于新的安装目录来操作,就可以通过这个参数来设置新的前缀路径,例如 nginx -p /usr/local/nginx/ 。
-e filename:可以设定 nginx 的错误日志文件路径及名称,改变默认记录错误日志的位置(默认是 /var/log/nginx/error.log ),如果需要将错误日志存放到其他文件中便于管理和查看,可使用该参数进行设置。
-c filename:用来明确指定 nginx 的配置文件路径及文件名,若你的配置文件不是在默认位置(/etc/nginx/nginx.conf ),或者同时存在多个配置文件想指定使用某一个时,就用这个参数来指定,比如 nginx -c /myconfig/nginx_custom.conf 。
-g directives:用于设置一些全局指令,这些指令不在常规的配置文件里定义,而是通过命令行直接添加,不过使用这个参数相对比较复杂,需要对 nginx 的指令体系比较熟悉,常用于一些特定的个性化配置需求场景。
通过掌握这些常用参数的功能和用法,就能更灵活、准确地使用 nginx 命令来管理和操作 nginx 服务了。
​
​
小屁现在习惯性使用nginx命令来控制nginx服务了
nginx -qt                   #检查配置文件是否有错,无错无内容输出
nginx                       #启动
nginx -s stop               #关闭
nginx -s quit               #优雅终止
nginx -s reload             #重载
nginx -s stop && nginx      #重启(使用较少)

二、Nginx配置文件解析

bash 复制代码
先看一眼都有啥?
[root@web01 nginx]#cat nginx.conf
​
#user  nobody;
worker_processes  1;
​
#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;
​
#pid        logs/nginx.pid;
​
​
events {
    worker_connections  1024;
}
​
​
http {
    include       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  logs/access.log  main;
​
    sendfile        on;
    #tcp_nopush     on;
​
    #keepalive_timeout  0;
    keepalive_timeout  65;
​
    #gzip  on;
​
    server {
        listen       80;
        server_name  localhost;
​
        #charset koi8-r;
​
        #access_log  logs/host.access.log  main;
​
        location / {
            root   html;
            index  index.html index.htm;
        }
​
        #error_page  404              /404.html;
​
        # redirect server error pages to the static page /50x.html
        #
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }
​
        # proxy the PHP scripts to Apache listening on 127.0.0.1:80
        #
        #location ~ \.php$ {
        #    proxy_pass   http://127.0.0.1;
        #}
​
        # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
        #
        #location ~ \.php$ {
        #    root           html;
        #    fastcgi_pass   127.0.0.1:9000;
        #    fastcgi_index  index.php;
        #    fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;
        #    include        fastcgi_params;
        #}
​
        # deny access to .htaccess files, if Apache's document root
        # concurs with nginx's one
        #
        #location ~ /\.ht {
        #    deny  all;
        #}
    }
​
​
    # another virtual host using mix of IP-, name-, and port-based configuration
    #
    #server {
    #    listen       8000;
    #    listen       somename:8080;
    #    server_name  somename  alias  another.alias;
​
    #    location / {
    #        root   html;
    #        index  index.html index.htm;
    #    }
    #}
​
​
    # HTTPS server
    #
    #server {
    #    listen       443 ssl;
    #    server_name  localhost;
​
    #    ssl_certificate      cert.pem;
    #    ssl_certificate_key  cert.key;
​
    #    ssl_session_cache    shared:SSL:1m;
    #    ssl_session_timeout  5m;
​
    #    ssl_ciphers  HIGH:!aNULL:!MD5;
    #    ssl_prefer_server_ciphers  on;
​
    #    location / {
    #        root   html;
    #        index  index.html index.htm;
    #    }
    #}
​
}
nginx的配置文件又臭又长,那么他们的意义何在呢?

1.ngnix区块关系

bash 复制代码
cat /etc/nginx/nginx.conf
三大区块;同级关系,类似公司股东
[root@web01 nginx]#cat nginx.conf 
# 核心区块
user  nginx;                # 启动nginx的虚拟用户 默认已经存在了
worker_processes  auto;     # 启动子进程的数量 auto以cpu的内核数为准
error_log  /var/log/nginx/error.log notice; # 错误日志所在的日志
pid        /var/run/nginx.pid;              # 进程PID所存放的目录
# 事件模块
events {
 worker_connections  25532;              # 进程的最大连接数
}
 # http模块
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;   # nginx的访问日志
sendfile       on;       #文件高效传参
#tcp_nopush    on;      
keepalive_timeout  65;      #长连接的超时时间                    
#gzip  on;                    #是否开启压缩
include /etc/nginx/conf.d/*.conf;              # 包含了conf.d目录下所有的.conf  将*.conf内容移动到了当前的文件中
}
​
​
1)autoindex  对所有的包含的server location区块生效
    server区块 配置的具体的业务
    2)autoindex 对当前的server和包含的laocation区块生效
          location区块(路径匹配)
           3)autoindex 只对当前的location区块生效
    server     配置具体的业务 小霸王
          location区块(路径匹配)
location /download{
    charset utf-8,gbk;          #字符集解决中文乱码问题
    alias /package;             #指定到package目录里拿(实际代码存在的位置)
    autoindex on;               #开启目录列表(将代码目录下的index.html移除,否则优先寻找index.html)
    autoindex_loacltime on;     #以系统时间为准显示浏览器
    autoindex_exact_size off;   #人类可读文件大小
    auth_basic "test";          #密码验证登录描述
    auth_basic_user_file auth_pass; #指定密码文件的位置
    allow 10.0.0.1;             #允许哪些IP地址可以访问此location
    deny all;                   #拒绝所有
}
location中指定路径方式有两种:
1.root 指定路径
    location /download {
        root /package;
        autoindex on;
    }
实际代码存储的位置是: /package/dlownload
2.alias指定路径 指哪去哪里拿
    location /download {
        alias /package;
        autoindex on;
    }
实际代码存储的位置是: /package

2、密码验证

bash 复制代码
用户名密码登录验证模块:
auth_basic  # 描述信息
auth_basic_user_file  # 指定用户和密码文件所在的路径
密码文件需要使用htpasswd生成
1.安装httpd-tools
[root@web01 ~]#yum -y install httpd-tools
2.生成密码文件
[root@web01 ~]#htpasswd -b -c /etc/nginx/auth_pass yunzhongzi yunzhongzi
Adding password for user yunzhongzi
[root@web01 ~]#cat /etc/nginx/auth_pass 
yunzhongzi:$apr1$AbYbPSQw$Lf5axSNt04BiNRxblGT9o1
3.配置nginx
location模块中配置:
        auth_basic "test";
        auth_basic_user_file auth_pass;

3、IP地址限制

bash 复制代码
限制方式两种:
        先允许后拒绝:
                    allow 10.0.0.1;     #10.0.0.1可以访问
                    deny all;           #其他所有拒绝
        先拒绝后允许:
                    deny 10.0.0.1;      #10.0.0.1拒绝访问
                    allow all;          #其他IP允许访问
语法两条:
        allow 允许访问的IP
        deny  不允许访问的IP

4、Nginx状态模块

bash 复制代码
nginx状态模块:              #用于查看 Nginx 服务器状态信息
    stub_status
配置:
    location /nginx_status {
        stub_status;
    }
浏览器访问位置 
www.game.com/nginx_status

5、连接限制,请求限制

bash 复制代码
连接限制
limit_conn
请求限制
    http{   #http层,设置
        # Limit settings
        limit_conn_zone $remote_addr zone=conn_zone:10m;
            server{ #server层调用
              #连接限制,限制同时最高1个连接
              limit_conn conn_zone 1;
             }
    }
limit_request
     # http标签段定义请求限制, rate限制速率,限制一秒钟最多一个IP请求
http {
    limit_req_zone $binary_remote_addr zone=req_zone:10m rate=1r/s;
}
server {
    listen 80;
    server_name module.yunzhongzi.com;
    # 1r/s只接收一个请求,其余请求拒绝处理并返回错误码给客户端
    #limit_req zone=req_zone;
​
    # 请求超过1r/s,剩下的将被延迟处理,请求数超过burst定义的数量, 多余的请求返回503
    limit_req zone=req_zone burst=3 nodelay;
    location / {
        root /code;
        index index.html;
    }
}

6、loaction匹配规则

bash 复制代码
[root@web01 conf.d]#cat test.conf 
server {
    listen 80;
    server_name test.yunzhongzi.com;
    default_type text/html;
    location = / {
    return 200 "configuration A";
    }
    location  / {
    return 200 "configuration B";
    }
​
    location /documents/ {
    return 200 "configuration C";
    }
​
    location ^~ /images/ {
    return 200 "configuration D";
    }
​
    location ~* \.(gif|jpg|jpeg)$ {
    return 200 "configuration E";
    }
}
[root@web01 conf.d]#curl test.yunzhongzi.com/
configuration A
[root@web01 conf.d]#
[root@web01 conf.d]#curl test.yunzhongzi.com
configuration A
[root@web01 conf.d]#
[root@web01 conf.d]#curl test.yunzhongzi.com/index.html
configuration B
[root@web01 conf.d]#
[root@web01 conf.d]#curl test.yunzhongzi.com/documents/document.html
configuration C
[root@web01 conf.d]#
[root@web01 conf.d]#curl test.yunzhongzi.com/images/1.gif
configuration D
[root@web01 conf.d]#
[root@web01 conf.d]#curl test.yunzhongzi.com/documents/1.jpg
configuration E
[root@web01 conf.d]#

location匹配规则优先级

bash 复制代码
1.等号最高          =
2.以......开头         ^~
3.区分大小写匹配     ~
4.不区分大小写      ~*
5.默认匹配          /

nginx配置文件的解析就到这里了,明天来点干货,部署服务,LNMP架构~~~~


想成为大佬,就要从小白开始,从0开始,一点一点的积累,慢慢成长,明天你就是大佬!!想学习更多麒麟操作系统的知识,关注小屁,让你成为运维老鸟~~~~~

相关推荐
糖果店的幽灵12 小时前
【DeepAgents 从入门到精通】Context Management 上下文管理
java·人工智能·后端·spring·中间件·langgraph·deepagents
CodexDave14 小时前
MySQL事务隔离级别与MVCC机制解析
前端·数据库·mysql·nginx·性能优化·负载均衡
一叶龙洲14 小时前
wslg打开Ubuntu24.04默认打开图形界面
linux·服务器·数据库·ubuntu
CCPC不拿奖不改名14 小时前
大模型推理架构与开源生态知识整理
数据库·windows·python·架构·langchain·开源·github
敖行客 Allthinker16 小时前
Parallels Ubuntu虚拟机项目如何让手机访问?完整解决方案
linux·运维·ubuntu
keyipatience17 小时前
线程栈与TLS和线程互斥
java·linux·服务器·开发语言·ubuntu
元Y亨H17 小时前
生产环境监控与故障应急处理(5-5-5 标准)指南
运维
j7~17 小时前
【Linux】二十二.《Linux 信号机制完全指南:表示、捕捉与处理》
linux·信号处理·volatile·可入重函数·保存信号
踏月的造梦星球17 小时前
达梦数据库执行计划与性能分析入门:EXPLAIN、AUTOTRACE 与 ET
服务器·数据库·oracle
heimeiyingwang18 小时前
【架构实战】可观测性三支柱:日志、指标、链路的融合
elasticsearch·架构·kubernetes