nginx

1. nginx简介

nginx(发音同engine x)是一款轻量级的Web服务器/反向代理服务器及电子邮件(IMAP/POP3)代理服务器,并在一个BSD-like协议下发行。

nginx由俄罗斯的程序设计师Igor Sysoev所开发,最初供俄国大型的入口网站及搜寻引擎Rambler使用。

第一个公开版本0.1.0发布于2004年10月4日。其将源代码以类BSD许可证的形式发布,因它的稳定性、丰富的功能集、示例配置文件和低系统资源的消耗而闻名。2011年6月1日,nginx 1.0.4发布。

nginx的特点是占有内存少,并发能力强,事实上nginx的并发能力确实在同类型的网页服务器中表现较好,中国大陆使用nginx网站用户有:百度、京东、新浪、网易、腾讯、淘宝等。

2. nginx的特性与优点

2.1 nginx的特性

nginx是一个很牛的高性能Web和反向代理服务器,它具有很多非常优越的特性:

  • 在高连接并发的情况下,nginx是Apache服务器不错的替代品,能够支持高达50000个并发连接数的响应
  • 使用epoll and kqueue作为开发模型
  • nginx作为负载均衡服务器:nginx既可在内部直接支持和PHP程序对外进行服务,也可支持作为HTTP代理服务器对外进行服务
  • nginx采用C语言进行编写,不论系统资源开销还是CPU使用效率都比Perlbal要好很多

2.2 nginx的优点

  • 高并发连接:官方测试能够支撑5万并发连接,在实际生产环境中跑到2-3万并发连接数
  • 内存消耗少:在3万并发连接下,开启的10个nginx进程才消耗150M内存(15M*10=150M)
  • 配置文件非常简单:风格跟程序一样通俗易懂
  • 成本低廉:nginx为开源软件,可以免费使用。而购买F5 BIG-IP、NetScaler等硬件负载均衡交换机则需要十多万至几十万人民币
  • 支持Rewrite重写规则:能够根据域名、URL的不同,将HTTP请求分到不同的后端服务器群组
  • 内置的健康检查功能:如果Nginx Proxy后端的某台Web服务器宕机了,不会影响前端访问
  • 节省带宽:支持GZIP压缩,可以添加浏览器本地缓存的Header头
  • 稳定性高:用于反向代理,宕机的概率微乎其微
  • 模块化设计:模块可以动态编译
  • 外围支持好:文档全,二次开发和模块较多
  • 支持热部署:可以不停机重载配置文件
  • 支持事件驱动、AIO(AsyncIO,异步IO)、mmap(Memory Map,内存映射)等性能优化

3. nginx的功能及应用类别

3.1 nginx的基本功能

  • 静态资源的web服务器,能缓存打开的文件描述符
  • http、smtp、pop3协议的反向代理服务器
  • 缓存加速、负载均衡
  • 支持FastCGI(fpm,LNMP),uWSGI(Python)等
  • 模块化(非DSO机制),过滤器zip、SSI及图像的大小调整
  • 支持SSL

3.2 nginx的扩展功能

  • 基于名称和IP的虚拟主机
  • 支持keepalive
  • 支持平滑升级
  • 定制访问日志、支持使用日志缓冲区提高日志存储性能
  • 支持URL重写
  • 支持路径别名
  • 支持基于IP及用户的访问控制
  • 支持速率限制,支持并发数限制

3.3 nginx的应用类别

  • 使用nginx结合FastCGI运行PHP、JSP、Perl等程序
  • 使用nginx作反向代理、负载均衡、规则过滤
  • 使用nginx运行静态HTML网页、图片
  • nginx与其他新技术的结合应用

4. nginx的模块与工作原理

nginx由内核和模块组成。其中,内核的设计非常微小和简洁,完成的工作也非常简单,仅仅通过查找配置文件将客户端请求映射到一个location block(location是nginx配置中的一个指令,用于URL匹配),而在这个location中所配置的每个指令将会启动不同的模块去完成相应的工作。

4.1 nginx的模块分类

nginx的模块从结构上分为核心模块、基础模块和第三方模块

  • HTTP模块、EVENT模块和MAIL模块等属于核心模块
  • HTTP Access模块、HTTP FastCGI模块、HTTP Proxy模块和HTTP Rewrite模块属于基本模块
  • HTTP Upstream模块、Request Hash模块、Notice模块和HTTP Access Key模块属于第三方模块

用户根据自己的需要开发的模块都属于第三方模块。正是有了如此多模块的支撑,nginx的功能才会如此强大

nginx模块从功能上分为三类,分别是:

  • Handlers(处理器模块)。此类模块直接处理请求,并进行输出内容和修改headers信息等操作。handlers处理器模块一般只能有一个
  • Filters(过滤器模块)。此类模块主要对其他处理器模块输出的内容进行修改操作,最后由nginx输出
  • Proxies(代理器模块)。就是nginx的HTTP Upstream之类的模块,这些模块主要与后端一些服务比如fastcgi等操作交互,实现服务代理和负载均衡等功能

nginx模块分为:核心模块、事件模块、标准Http模块、可选Http模块、邮件模块、第三方模块和补丁等

  • nginx基本模块:所谓基本模块,指的是nginx默认的功能模块,它们提供的指令,允许你使用定义nginx基本功能的变量,在编译时不能被禁用,包括:
    • 核心模块:基本功能和指令,如进程管理和安全。常见的核心模块指令,大部分是放置在配置文件的顶部(每行命令开头的上一行)
    • 事件模块:在Nginx内配置网络使用的能力。常见的events(事件)模块指令,大部分是放置在配置文件的顶部
    • 配置模块:提供包含机制

具体的指令,请参考nginx官方文档

4.2 nginx的工作原理

nginx的模块直接被编译进nginx,因此属于静态编译方式。

启动nginx后,nginx的模块被自动加载,与Apache不一样,首先将模块编译为一个so文件,然后在配置文件中指定是否进行加载。

在解析配置文件时,nginx的每个模块都有可能去处理某个请求,但是同一个处理请求只能由一个模块来完成。

nginx的进程架构:
启动nginx时,会启动一个Master进程,这个进程不处理任何客户端的请求,主要用来产生worker线程,一个worker线程用来处理n个request

在这里插入图片描述

下图展示了nginx模块一次常规的HTTP请求和响应的过程

在这里插入图片描述

下图展示了基本的WEB服务请求步骤

在这里插入图片描述

(1)建立连接 — 接受一个客户端连接,或者如果不希望与这个客户端建立连接,就将其关闭。
(2)接收请求 — 从网络中读取一条 HTTP 请求报文。
(3)处理请求 — 对请求报文进行解释,并采取行动。
(4)访问资源 — 访问报文中指定的资源。
(5)构建响应 — 创建带有正确首部的 HTTP 响应报文。
(6)发送响应 — 将响应回送给客户端。
(7)记录事务处理过程 — 将与已完成事务有关的内容记录在一个日志文件中。

5.nginx的安装与配置

5.1 nginx的安装

//关闭防火墙与SELINUX
[root@localhost ~]# systemctl disable --now firewalld
[root@localhost ~]# sed -ri 's/^(SELINUX=).*/\1disabled/g' /etc/selinux/config
[root@localhost ~]# setenforce 0
[root@localhost ~]# reboot

//创建系统用户nginx
[root@localhost ~]# useradd -r -M -s /sbin/nologin nginx

//安装依赖环境
[root@localhost ~]# yum -y install pcre-devel openssl openssl-devel gd-devel gcc gcc-c++
[root@localhost ~]# yum -y groups mark install 'Development Tools'

//创建日志存放目录
[root@localhost ~]# mkdir -p /var/log/nginx
[root@localhost ~]# chown -R nginx.nginx /var/log/nginx

//下载nginx
[root@localhost ~]# cd /usr/src/
[root@localhost src]# wget http://nginx.org/download/nginx-1.21.3.tar.gz
[root@localhost src]# ls
debug  kernels  nginx-1.21.3

//编译安装
[root@localhost src]# ls
debug  kernels  nginx-1.21.3.tar.gz
[root@localhost src]# tar xf nginx-1.21.3.tar.gz 
[root@localhost src]# cd nginx-1.21.3
[root@localhost nginx-1.21.3]# ./configure \
--prefix=/usr/local/nginx \
--user=nginx \
--group=nginx \
--with-debug \
--with-http_ssl_module \
--with-http_realip_module \
--with-http_image_filter_module \
--with-http_gunzip_module \
--with-http_gzip_static_module \
--with-http_stub_status_module \
--http-log-path=/var/log/nginx/access.log \
--error-log-path=/var/log/nginx/error.log

[root@localhost nginx-1.20.1]# make -j $(grep 'processor' /proc/cpuinfo | wc -l) && make install
安装过程略....

//配置环境变量
[root@localhost ~]# echo 'export PATH=/usr/local/nginx/sbin:$PATH' > /etc/profile.d/nginx.sh
[root@localhost ~]# . /etc/profile.d/nginx.sh
[root@localhost ~]# which nginx
/usr/local/nginx/sbin/nginx

//开机自启
[root@localhost ~]# cat > /usr/lib/systemd/system/nginx.service << EOF
[Unit]
Description=nginx
After=network.target
  
[Service]
Type=forking
ExecStart=/usr/local/nginx/sbin/nginx
ExecStop=/usr/local/nginx/sbin/nginx -s stop
ExecReload=/bin/kill -HUP  

[Install]
WantedBy=multi-user.target
EOF

[root@localhost ~]# systemctl daemon-reload
#开启服务
[root@localhost ~]# systemctl enable --now nginx
[root@localhost ~]# systemctl status nginx
● nginx.service - nginx
   Loaded: loaded (/usr/lib/systemd/system/nginx.service; enabled; vendor preset: disabled)
   Active: active (running) since Tue 2021-10-26 01:40:12 CST; 4min 47s ago
  Process: 995 ExecStart=/usr/local/nginx/sbin/nginx (code=exited, status=0/SUCCESS)
 Main PID: 1010 (nginx)
    Tasks: 2 (limit: 11300)
   Memory: 7.2M
   CGroup: /system.slice/nginx.service
           ├─1010 nginx: master process /usr/local/nginx/sbin/nginx
           └─1013 nginx: worker process

1026 01:40:10 localhost.localdomain systemd[1]: Starting nginx...
1026 01:40:12 localhost.localdomain systemd[1]: Started nginx.

[root@localhost ~]# ss -anlt
State              Recv-Q             Send-Q                         Local Address:Port                         Peer Address:Port             
LISTEN             0                  128                                  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                                   [::]:*                


在这里插入图片描述

5.2 nginx安装后的相关命令

//服务控制方式,使用nginx命令
    -t  //检查配置文件语法
    -v  //输出nginx的版本
    -c  //指定配置文件的路径
    -s  //发送服务控制信号,可选值有{stop|quit|reopen|reload}
    
    
-t
[root@localhost ~]# nginx -t
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful

-v
[root@localhost ~]# nginx -v
nginx version: nginx/1.21.3
    
-c
[root@localhost ~]# cd /usr/local/nginx/conf/
[root@localhost conf]# pwd
/usr/local/nginx/conf
[root@localhost conf]# cp mime.types nginx.conf /opt/
[root@localhost conf]# nginx -s stop; nginx -c /opt/nginx.conf
[root@localhost conf]# ps -ef | grep nginx
root       17763    1515  0 01:50 pts/0    00:00:00 grep --color=auto nginx   
            
[root@localhost conf]# nginx -s stop; nginx 
[root@localhost conf]# ps -ef | grep nginx
root       20042       1  0 01:51 ?        00:00:00 nginx: master process nginx
nginx      20043   20042  0 01:51 ?        00:00:00 nginx: worker process
root       20129    1515  0 01:51 pts/0    00:00:00 grep --color=auto nginx

-s
[root@localhost conf]# nginx -s quit
[root@localhost conf]# ss -anlt
State              Recv-Q             Send-Q                         Local Address:Port                         Peer Address:Port             
LISTEN             0                  128                                  0.0.0.0:22                                0.0.0.0:*                
LISTEN             0                  128                                     [::]:22                                   [::]:*            

6.httpd,nginx服务的网页存放目录

安装方式httpdnginx
yum/war/www/html//usr/share/nginx/html/
源码安装目录下的/htdocs安装目录下的/html

7 nginx的配置文件详解

主配置文件:/usr/local/nginx/conf/nginx.conf

  • 默认启动nginx时,使用的配置文件是:安装路径/conf/nginx.conf文件
  • 可以在启动nginx时通过-c选项来指定要读取的配置文件

nginx常见的配置文件及其作用

配置文件作用
nginx.confnginx的基本配置文件
mime.typesMIME类型关联的扩展文件
fastcgi.conf与fastcgi相关的配置
proxy.conf与proxy相关的配置
sites.conf配置nginx提供的网站,包括虚拟主机

7.1 nginx.conf配置详解

nginx.conf的内容分为以下几段:

  • main配置段:全局配置段。其中main配置段中可能包含event配置段
  • event {}:定义event模型工作特性
  • http {}:定义http协议相关的配置

配置指令:要以分号结尾,语法格式如下:

derective value1 [value2 ...];
1

支持使用变量:

  • 内置变量:模块会提供内建变量定义
  • 自定义变量:set var_name value

7.2 用于调试、定位问题的配置参数

daemon {on|off};    		 //是否以守护进程方式运行nginx,调试时应设置为off
master_process {on|off};     //是否以master/worker模型来运行nginx,调试时可以设置为off
error_log 位置 级别;  	 	 //配置错误日志
123

error_log里的位置和级别能有以下可选项:

位置级别
file stderr syslog:server=address[,parameter=value] memory:sizedebug:若要使用debug级别,需要在编译nginx时使用–with-debug选项 info notice warn error crit alert emerg

7.3 正常运行必备的配置参数

user USERNAME [GROUPNAME];    	//指定运行worker进程的用户和组
pid /path/to/pid_file;    		//指定nginx守护进程的pid文件
worker_rlimit_nofile number;    //设置所有worker进程最大可以打开的文件数,默认为1024
worker_rlimit_core size;    	//指明所有worker进程所能够使用的总体的最大核心文件大小,保持默认即可
  • user、pid
//nginx安装过后配置文件中的user默认是nobody,但是配置文件中user参数是注释掉的,即使我们把注释去掉,默认user也不是nobody,是nginx
[root@localhost ~]#  ps -ef |grep nginx 
root      13317      1  0 23:17 ?        00:00:00 nginx: master process nginx
nginx     13318  13317  0 23:17 ?        00:00:00 nginx: worker process
nginx     13319  13317  0 23:17 ?        00:00:00 nginx: worker process
nginx     13320  13317  0 23:17 ?        00:00:00 nginx: worker process
root      13395   1488  0 23:17 pts/0    00:00:00 grep --color=auto nginx

[root@localhost ~]# cat /usr/local/nginx/conf/nginx.conf

user  nginx nginx;
worker_processes  3;

#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;

pid        logs/nginx.pid;		#取消注释

......
  • worker_rlimit_nofile number
    Linux是有文件句柄限制的(open files),一般默认是1024,当超过这个数量便会报 Too many open files错误,修改nginx参数worker_rlimit_nofile number时,同时也需要修改系统的open file,使用命令ulimit -a可以查看句柄数
[root@localhost ~]# vim /usr/local/nginx/conf/nginx.conf
......
worker_rlimit_nofile 65535;
......
[root@localhost ~]# nginx -s reload

//增大系统允许打开的文件数,修改系统配置文件
[root@localhost ~]# vim /etc/security/limits.conf 
[root@localhost ~]# tail -2 /etc/security/limits.conf 
*    soft    nofile    65535    #末尾添加此行
*    hard    nofile    65535    #末尾添加此行

[root@localhost ~]# ulimit -a 
core file size          (blocks, -c) 0
data seg size           (kbytes, -d) unlimited
scheduling priority             (-e) 0
file size               (blocks, -f) unlimited
pending signals                 (-i) 14996
max locked memory       (kbytes, -l) 64
max memory size         (kbytes, -m) unlimited
open files                      (-n) 1024
pipe size            (512 bytes, -p) 8
POSIX message queues     (bytes, -q) 819200
real-time priority              (-r) 0
stack size              (kbytes, -s) 8192
cpu time               (seconds, -t) unlimited
max user processes              (-u) 14996
virtual memory          (kbytes, -v) unlimited
file locks                      (-x) unlimited

//设置完成以后重开一个终端或者重启即可生效
[root@localhost ~]# ulimit -a 
core file size          (blocks, -c) 0
data seg size           (kbytes, -d) unlimited
scheduling priority             (-e) 0
file size               (blocks, -f) unlimited
pending signals                 (-i) 14996
max locked memory       (kbytes, -l) 64
max memory size         (kbytes, -m) unlimited
open files                      (-n) 65535
pipe size            (512 bytes, -p) 8
POSIX message queues     (bytes, -q) 819200
real-time priority              (-r) 0
stack size              (kbytes, -s) 8192
cpu time               (seconds, -t) unlimited
max user processes              (-u) 14996
virtual memory          (kbytes, -v) unlimited
file locks                      (-x) unlimited

7.4 错误页面配置

[root@localhost ~]# vim /usr/local/nginx/conf/nginx.conf
......
48         error_page  404             /404.html;	#取消注释
......
[root@localhost ~]# vim /usr/local/nginx/html/404.html
[root@localhost ~]# cat /usr/local/nginx/html/404.html
404 de cuo wu yiemian
[root@localhost ~]# nginx -s  reload

输入一个不存在的网页页面测试
在这里插入图片描述

[root@localhost ~]# vim /usr/local/nginx/conf/nginx.conf
......
 error_page 404 =200 /404.html  
......
[root@localhost ~]# nginx -s  reload

在这里插入图片描述

7.5平滑升级

1.获取老版本的编译参数-V

[root@localhost ~]# nginx  -V
nginx version: nginx/1.21.3
built by gcc 4.8.5 20150623 (Red Hat 4.8.5-44) (GCC) 
built with OpenSSL 1.0.2k-fips  26 Jan 2017
TLS SNI support enabled
configure arguments: --prefix=/usr/local/nginx --user=nginx --group=nginx --with-debug --with-http_ssl_module --with-http_realip_module --with-http_image_filter_module --with-http_gunzip_module --with-http_gzip_static_module --with-http_stub_status_module --http-log-path=/var/log/nginx/access.log --error-log-path=/var/log/nginx/error.log

2.获取新版本或新功能的软件包
下载地址 github.com

[root@localhost ~]#  cd /usr/src/
[root@localhost src]# ls
debug  echo-nginx-module-master.tar  kernels  nginx-1.21.3
[root@localhost src]# tar xf echo-nginx-module-master.tar 
[root@localhost src]# ls
debug  echo-nginx-module-master  echo-nginx-module-master.tar  kernels  nginx-1.21.3

3.对新功能或新版本的软件包进行编译

[root@localhost src]# cd nginx-1.21.3/
[root@nginx nginx-1.21.3]# ./configure   --prefix=/usr/local/nginx --user=nginx --group=nginx --with-debug --with-http_ssl_module --with-http_realip_module --with-http_image_filter_module --with-http_gunzip_module --with-http_gzip_static_module --with-http_stub_status_module --http-log-path=/var/log/nginx/access.log --error-log-path=/var/log/nginx/error.log --add-module=../echo-nginx-module-master
[root@nginx nginx-1.21.3]# make

4.备份老程序

[root@localhost nginx-1.21.3]# ll objs/nginx /usr/local/nginx/sbin/nginx 
-rwxr-xr-x. 1 root root 6842552 1028 13:09 objs/nginx
-rwxr-xr-x. 1 root root 6842552 1028 13:18 /usr/local/nginx/sbin/nginx
[root@localhost nginx-1.21.3]# cp /usr/local/nginx/sbin/nginx  /opt/
[root@localhost nginx-1.21.3]# ls /opt/
mime.types  nginx  nginx.conf

5.停掉老程序并用新程序使用老程序的配置文件进行启动

[root@localhost nginx-1.21.3]#  nginx -s stop;objs/nginx -c /usr/local/nginx/conf/nginx.conf
[root@localhost nginx-1.21.3]# ps -ef|grep nginx
root      62044   1487  0 00:00 pts/0    00:00:00 grep --color=auto nginx

6.检验功能,若无问题即用新程序替换老程序

[root@localhost nginx-1.21.3]# objs/nginx -t
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful
[root@localhost nginx-1.21.3]# objs/nginx  -s reload

7.测试

[root@localhost ~]# vim /usr/local/nginx/conf/nginx.conf

		location / {
            root   html;
            index  index.html index.htm;
        }

        location /test {
            echo "test";
        }
[root@localhost nginx-1.21.3]# objs/nginx -t
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful
[root@localhost nginx-1.21.3]# objs/nginx -s reload

[root@localhost nginx-1.21.3]# curl http://192.168.47.115/test
test

[root@localhost nginx-1.21.3]# \cp objs/nginx /usr/local/nginx/sbin/nginx
[root@localhost nginx-1.21.3]# ll objs/nginx /usr/local/nginx/sbin/nginx 
-rwxr-xr-x. 1 root root 6842552 1028 13:09 objs/nginx
-rwxr-xr-x. 1 root root 6842552 1028 13:18 /usr/local/nginx/sbin/nginx
[root@localhost nginx-1.21.3]# objs/nginx -s stop;nginx
[root@localhost nginx-1.21.3]# ps -ef | grep nginx
root       87438       1  0 13:18 ?        00:00:00 nginx: master process nginx
nginx      87439   87438  0 13:18 ?        00:00:00 nginx: worker process
root       87633    8710  0 13:18 pts/2    00:00:00 grep --color=auto nginx
[root@localhost nginx-1.21.3]# 

7.6 location配置

location区段,通过指定模式来与客户端请求的URI相匹配

//功能:允许根据用户请求的URI来匹配定义的各location,匹配到时,此请求将被相应的location配置块中的配置所处理,例如做访问控制等功能

//语法:location [ 修饰符 ] pattern {......}

常用修饰符说明:

修饰符功能
=精确匹配
~正则表达式模式匹配,区分大小写
~*正则表达式模式匹配,不区分大小写
^~前缀匹配,类似于无修饰符的行为,也是以指定模块开始,不同的是,如果模式匹配,那么就停止搜索其他模式了,不支持正则表达式
@定义命名location区段,这些区段客户端不能访问,只可以由内部产生的请求来访问,如try_files或error_page等

没有修饰符表示必须以指定模式开始,如:

[root@localhost local]# vim nginx/conf/nginx.conf
		location / {
            root   html;
            index  index.html index.htm;
        }

        location /test {
            echo "test";
        }

[root@localhost ~]# nginx -s reload

那么如下内容就可正确匹配:
[root@localhost ~]# curl http://192.168.47.115/test
test
[root@localhost ~]# curl http://192.168.47.115/test/
test
[root@localhost ~]# curl http://192.168.47.115/test?test
test

=:表示必须与指定的模式精确匹配,如:

[root@localhost ~]# vim /usr/local/nginx/conf/nginx.conf
......
        location / {
            root   html;
            index  index.html index.htm;
        }
        location /test {				#匹配/test下的所有
            echo "test";
        }
        location =/test {
            echo "111";
        }
[root@localhost ~]# nginx -s reload

那么如下内容就可正确匹配:
[root@localhost ~]# curl http://192.168.47.115/test
111

如下内容则无法匹配:
[root@localhost ~]# curl http://192.168.47.115/test/
test
[root@localhost ~]# curl http://192.168.47.115/test/abc
test
[root@localhost ~]# curl http://192.168.47.115/testtest
test

~:表示指定的正则表达式要区分大小写,如:

[root@localhost ~]# vim /usr/local/nginx/conf/nginx.conf
......
        location / {
            root   html;
            index  index.html index.htm;
        }
        location /test {
            echo "test";
        }
        location ~ ^/test$ {
            echo "大小写";
        }
[root@localhost ~]# nginx -s reload

那么如下内容就可正确匹配:
[root@localhost ~]# curl http://192.168.47.115/test
大小写
如下内容则无法匹配:
[root@localhost ~]# curl http://192.168.47.115/test/
test
[root@localhost ~]# curl http://192.168.47.115/testkllk
test

~*:表示指定的正则表达式不区分大小写,如:

[root@localhost ~]# vim /usr/local/nginx/conf/nginx.conf
......
        location ~ ^/test$ {
            echo "大小写";
        }
        
[root@localhost ~]# nginx -s reload

那么如下内容就可正确匹配:
[root@localhost ~]# curl http://192.168.47.115/test
不分大小写
[root@localhost ~]# curl http://192.168.47.115/TEST
不分大小写
[root@localhost ~]# curl http://192.168.47.115/TEst
不分大小写

如下内容则无法匹配:
[root@localhost ~]# curl http://192.168.47.115/TEst/
<html>
<head><title>404 Not Found</title></head>
<body>
<center><h1>404 Not Found</h1></center>
<hr><center>nginx/1.21.3</center>
</body>
</html>

[root@localhost ~]# curl http://192.168.47.115/testas
<html>
<head><title>404 Not Found</title></head>
<body>
<center><h1>404 Not Found</h1></center>
<hr><center>nginx/1.21.3</center>
</body>
</html>

~:类似于无修饰符的行为,也是以指定模式开始,不同的是,如果模式匹配,则停止搜索其他模式

[root@localhost ~]# vim /usr/local/nginx/conf/nginx.conf
......
        location / {
            root   html;
            index  index.html index.htm;
        }
        location /test {
            echo "无";
        }
        location ~ ^/test$ {
            echo "分大小写";
        }

        location ~* ^/test$ {
            echo "不分大小写";
        }

[root@localhost ~]# nginx -s reload

那么如下内容就可正确匹配:
[root@localhost ~]# curl http://192.168.47.115/test
分大小写
[root@localhost ~]# curl http://192.168.47.115/tesT
不分大小写
[root@localhost ~]# curl http://192.168.47.115/test/[root@localhost ~]# curl http://192.168.47.115/test/abc[root@localhost ~]# curl http://192.168.47.115/testasda

查找顺序和优先级:由高到底依次为

  1. 带有=的精确匹配优先
  2. 正则表达式按照他们在配置文件中定义的顺序
  3. 带有^~修饰符的,开头匹配
  4. 带有~~*修饰符的,如果正则表达式与URI匹配
  5. 没有修饰符的精确匹配

优先级次序如下:

( location = 路径 ) --> ( location ^~ 路径 ) --> ( location ~ 正则 ) --> ( location ~* 正则 ) --> ( locatio

7.7访问控制

用于location段
allow:设定允许哪台或哪些主机访问,多个参数间则换行
deny:设定禁止哪台或哪些主机访问,多个参数间则换行

[root@localhost ~]# mkdir /usr/local/nginx/html/test -p
[root@localhost ~]# echo "tjjjjjjj" > /usr/local/nginx/html/test/index.html
[root@localhost ~]# nginx -s reload
[root@localhost ~]# vim /usr/local/nginx/conf/nginx.conf
        location /test {
            deny   192.168.47.1;	## 黑名单(除了自己谁都能访问)
            root   html;
            index  index.html;
        }


[root@localhost ~]# curl http://192.168.47.115/test/index.html
tjjjjjjj


在这里插入图片描述

7.8 基于用户认证

示例:

#安装httpd-tools
[root@localhost ~]# yum -y install httpd-tools
#生成用户和密码
[root@localhost ~]# htpasswd -c -m /usr/local/nginx/conf/.pass admin	
New password: 
Re-type new password: 
Adding password for user admin

[root@localhost ~]# cat /usr/local/nginx/conf/.pass 
admin:$apr1$aUt5SeD5$er68PUk.G2ZszwmUrUQ0Y0
[root@localhost ~]# vim /usr/local/nginx/conf/nginx.conf
......
        #access_log  logs/host.access.log  main;

        location / {
            root   html;
            index  index.html index.htm;
        }
        location /test {
            auth_basic "欢迎信息";
            auth_basic_user_file ".pass";		#指定文件
            root   html;
            index  index.html;
        }
[root@localhost ~]# nginx -s reload

在这里插入图片描述

7.9 https配置

[root@localhost ~]#  mkdir /etc/pki/CA
[root@localhost ~]#  cd /etc/pki/CA/
[root@localhost CA]# mkdir private
[root@localhost CA]# umask 077;openssl genrsa -out private/cakey.pem 2048
Generating RSA private key, 2048 bit long modulus (2 primes)
...................+++++
.........................+++++
e is 65537 (0x010001)

[root@localhost CA]# openssl req -new -x509 -key private/cakey.pem -out cacert.pem -days 365
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [XX]:cn
State or Province Name (full name) []:hb
Locality Name (eg, city) [Default City]:wh
Organization Name (eg, company) [Default Company Ltd]:jj
Organizational Unit Name (eg, section) []:jj
Common Name (eg, your name or your server's hostname) []:jj.example.com
Email Address []:1@1.com 

[root@localhost CA]# mkdir certs newcerts crl
[root@localhost CA]# touch index.txt && echo 01 > serial
[root@localhost CA]# cd /usr/local/nginx/
[root@localhost nginx]# ls
client_body_temp  conf  fastcgi_temp  html  logs  proxy_temp  sbin  scgi_temp  uwsgi_temp
[root@localhost nginx]# mkdir ssl
[root@localhost nginx]# cd /usr/local/nginx/ssl
[root@localhost ssl]# (umask 077;openssl genrsa -out nginx.key 2048)
Generating RSA private key, 2048 bit long modulus (2 primes)
.................................................................+++++
.+++++
e is 65537 (0x010001)
[root@localhost ssl]# ls
nginx.key

[root@localhost ssl]# openssl req -new -key nginx.key -days 365 -out nginx.csr
Ignoring -days; not generating a certificate
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [XX]:cn
State or Province Name (full name) []:hb
Locality Name (eg, city) [Default City]:wh
Organization Name (eg, company) [Default Company Ltd]:jj
Organizational Unit Name (eg, section) []:jj
Common Name (eg, your name or your server's hostname) []:jj.example
Email Address []:1@1.com

Please enter the following 'extra' attributes
to be sent with your certificate request
string is too short, it needs to be at least 4 bytes long
A challenge password []:
An optional company name []:

//CA签署客户端提交上来的证书
[root@localhost ssl]# openssl ca -in nginx.csr -out nginx.crt -days 365
Using configuration from /etc/pki/tls/openssl.cnf
Check that the request matches the signature
Signature ok
Certificate Details:
        Serial Number: 1 (0x1)
        Validity
            Not Before: Oct 28 06:31:27 2021 GMT
            Not After : Oct 28 06:31:27 2022 GMT
        Subject:
            countryName               = cn
            stateOrProvinceName       = hb
            organizationName          = jj
            organizationalUnitName    = jj
            commonName                = jj.example
            emailAddress              = 1@1.com
        X509v3 extensions:
            X509v3 Basic Constraints: 
                CA:FALSE
            Netscape Comment: 
                OpenSSL Generated Certificate
            X509v3 Subject Key Identifier: 
                8B:92:C8:21:14:1C:B4:96:9B:7D:8E:87:87:6D:7C:B5:69:55:06:C0
            X509v3 Authority Key Identifier: 
                keyid:1C:9D:6D:5E:B4:EE:D7:CD:C0:53:77:D5:F7:2D:6C:40:33:D3:BD:48

Certificate is to be certified until Oct 28 06:31:27 2022 GMT (365 days)
Sign the certificate? [y/n]:y


1 out of 1 certificate requests certified, commit? [y/n]y
Write out database with 1 new entries
Data Base Updated

[root@localhost ssl]# ls
nginx.crt  nginx.csr  nginx.key
[root@localhost ssl]# vim /usr/local/nginx/conf/nginx.conf
#在配置文件最后面,取消server模块的注释,并修改路径
    server {
        listen       443 ssl;
        server_name  localhost;

        ssl_certificate      /usr/local/nginx/ssl/nginx.crt;	#秘钥存放位置
        ssl_certificate_key  /usr/local/nginx/ssl/nginx.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;
        }
    }
[root@localhost ssl]# nginx -s reload

在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值