nginx的配置

配置参数

user USERNAME [GROUPNAME];    //指定运行worker进程的用户和组 ,指定以哪个组和哪个用户的身份去运行,组可写可不写
pid /path/to/pid_file;    //指定nginx守护进程的pid文件
worker_rlimit_nofile number;    //设置所有worker进程最大可以打开的文件数,默认为1024
worker_rlimit_core size;    //指明所有worker进程所能够使用的总体的最大核心文件大小,保持默认即可
user USERNAME [GROUPNAME]

因为这个地方注释了,所以依然是nginx用户去执行
[root@localhost conf]# head -2 nginx.conf

#user  nobody;

[root@localhost conf]# ps -ef | grep nginx
root       1088      1  0 14:14 ?        00:00:00 nginx: master process /usr/local/nginx/sbin/nginx
nginx      1089   1088  0 14:14 ?        00:00:00 nginx: worker process
nginx      1090   1088  0 14:14 ?        00:00:00 nginx: worker process
nginx      1091   1088  0 14:14 ?        00:00:00 nginx: worker process
root      45167   1363  0 17:40 pts/0    00:00:00 grep --color=auto nginx

最好改为nginx
[root@localhost conf]# head -2 nginx.conf

user  nginx nginx;
pid /path/to/pid_file; //指定nginx守护进程的pid文件

nginx的守护进程的文件存放的位置
守护进程的pid文件存放在安装目录下的logs下的 
nginx.pid  //默认存放的位置
[root@localhost conf]# vim nginx.conf
[root@localhost conf]# pwd
/usr/local/nginx/conf
9 #pid        logs/nginx.pid;   //虽然注释了但依然有效,当你使用这个某个文件时最好将注释取消,告诉系统文件位置
[root@localhost logs]# pwd
/usr/local/nginx/logs
[root@localhost logs]# ls
error.log  nginx.pid
worker_rlimit_nofile number; //设置所有worker进程最大可以打开的文件数,默认为1024
[root@localhost conf]# head -4 nginx.conf

user  nginx nginx;
worker_processes  3;
worker_rlimit_nofile 65535;
检查nginx语法看是否有问题
[root@localhost conf]# 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 conf]# systemctl restart nginx.service  //重启服务

因为我们刚才是设置的是nginx的访问数量,但是系统默认还是1024,需要将系统的1024也改为65535,猜可以生效,因为系统是包含nginx这个服务的

没修改之前的
[root@localhost security]# 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) 23060
max locked memory       (kbytes, -l) 64
max memory size         (kbytes, -m) unlimited
open files                      (-n) 1024

所以我们此时需要设置系统的支持的访问数量
[root@localhost security]# pwd
/etc/security
[root@localhost security]# tail -3 limits.conf   //在文件的最后一行添加下面两行内容
# End of file
* soft nofile 65535
* hard nofile 65535

此时在使用ulimit -a命令去查看
[root@localhost ~]# systemctl restart nginx.service
[root@localhost ~]# ulimit -a | grep -w 65535
open files                      (-n) 65535

优化性能的配置参数

这个是用来优化nginx的worker运行的效率
worker_processes n;    //启动n个worker进程,这里的n为了避免上下文切换,通常设置为cpu总核心数-1或等于总核心数
worker_cpu_affinity cpumask ...;    //将进程绑定到某cpu中,避免频繁刷新缓存
//cpumask:使用8位二进制表示cpu核心,如:
    0000 0001   //第一颗cpu核心
    0000 0010   //第二颗cpu核心
    0000 0100   //第三颗cpu核心
    0000 1000   //第四颗cpu核心
    0001 0000   //第五颗cpu核心
    0010 0000   //第六颗cpu核心
    0100 0000   //第七颗cpu核心
    1000 0000   //第八颗cpu核心
timer_resolution interval;    //计时器解析度。降低此值,可减少gettimeofday()系统调用的次数
worker_priority number;    //指明worker进程的nice值

worker_processes n; //启动n个worker进程,这里的n为了避免上下文切换,通常设置为cpu总核心数-1或等于总核心数
什么是上下文切换?
上下文切换就是从当前执行任务切换到另一个任务执行的过程。但是,为了确保下次能从正确的位置继续执行,在切换之前,会保存上一个任务的状态。下一次会接着上一个任务运行退出的地方接着运行。
为了避免上下文切换若你是8核的cpu给7核到nginx进程使用,剩余的给其他系统服务使用。

将进程绑定到某个cpu核心中
[root@localhost conf]# head -5 nginx.conf

user  nginx nginx;
worker_processes  1;
worker_cpu_affinity 0001 0010

然后使用top命令,再点击L键,输入nginx就可以找到nginx的进程
top - 08:14:24 up 6 min,  4 users,  load average: 0.15, 0.17, 0.11
Tasks: 135 total,   1 running, 134 sleeping,   0 stopped,   0 zombie
%Cpu(s):  0.8 us,  3.1 sy,  0.0 ni, 96.0 id,  0.0 wa,  0.0 hi,  0.1 si,  0.0 st
KiB Mem :  5927960 total,  5605320 free,   143528 used,   179112 buff/cache
KiB Swap:  6160380 total,  6160380 free,        0 used.  5544388 avail Mem 

 PR    PID USER      NI  %CPU    VIRT    RES    SHR S %MEM     TIME+ COMMAND                                P 
 20   1653 root       0   0.0  115932   2392   1644 S  0.0   0:00.01 bash                                   1 
 20   5173 root       0   0.0   77364   1356    240 S  0.0   0:00.00 nginx                                  2 
 20   5174 nginx      0   0.0   77740   2168    636 S  0.0   0:00.00 nginx                                  0 
 20  12626 root       0   0.0       0      0      0 S  0.0   0:00.00 kworker/0:

再按f键就会跳到这个页面,按上下左右的下键将光标移至P那一行,点击空格键选中,按q退出就可以看到,nginx进程使用的cpu了,并绑定成功,也不会进行上下文切换了
* PR      = Priority    PPID    = Parent Pr   nTH     = Number of   SUPGIDS = Supp Grou   nsUTS   = UTS names
* PID     = Process I   UID     = Effective * P       = Last Used   SUPGRPS = Supp Grou
* USER    = Effective   RUID    = Real User   TIME    = CPU Time    TGID    = Thread Gr
* NI      = Nice Valu   RUSER   = Real User   SWAP    = Swapped S   ENVIRON = Environme
* %CPU    = CPU Usage   SUID    = Saved Use   CODE    = Code Size   vMj     = Major Fa

  PID USER      PR  NI    VIRT    RES    SHR S  %CPU %MEM     TIME+ COMMAND                                            P 
  1604 root      20   0  116032   2656   1780 S   0.0  0.0   0:00.05 bash                                               2 
  1653 root      20   0  115932   2392   1644 S   0.0  0.0   0:00.01 bash                                               1 
  1771 root      20   0  162796   3068   1592 S   0.0  0.1   0:01.49 top                                                0 
  5173 root      20   0   77364   1356    240 S   0.0  0.0   0:00.00 nginx                                              2 
  5174 nginx     20   0   77740   2168    636 S   0.0  0.0   0:00.00 nginx         
worker_priority number; //指明worker进程的nice值


优先级分为两种一个实时优先级,一个相对优先级
能控制的优先级有40个数,-20到19 对应100-139
nice是数字越低优先级越高。
[root@localhost conf]# head -5 nginx.conf

user  nginx nginx;
worker_processes  1;
worker_cpu_affinity 0001 0010;
worker_priority -20;
[root@localhost conf]# systemctl restart nginx.service
使用top命令
11243 nginx      0 -20   77740   2188    640 S   0.0  0.0   0:00.00 nginx 

[root@localhost opt]# ps -elf | grep nginx
1 S root      11242      1  0  80   0 - 19341 sigsus 09:05 ?        00:00:00 nginx: master process /usr/local/nginx/sbin/nginx
5 S nginx     11243  11242  0  60 -20 - 19435 ep_pol 09:05 ?        00:00:00 nginx: worker process
0 S root      16510   2288  0  80   0 - 28206 pipe_w 09:08 pts/2    00:00:00 grep --c

事件相关的配置:event{}段中的配置参数

这些东西保持默认即可
accept_mutex {off|on};    //master调度用户请求至各worker进程时使用的负载均衡锁;on表示能让多个worker轮流地、序列化地去响应新请求
lock_file file;    //accept_mutex用到的互斥锁锁文件路径
use [epoll | rtsig | select | poll];    //指明使用的事件模型,建议让nginx自行选择
worker_connections #;    //每个进程能够接受的最大连接数

accept_mutex   //是互斥锁
worker_connection  //最好我们自行设置

worker_connections #; //每个进程能够接受的最大连接数

这是作为压测的工具
[root@localhost conf]# vim nginx.conf
14 events {
 15     worker_connections  20480;

[root@localhost conf]# systemctl restart nginx.service
若没有ab命令就请安装httpd-tools包组
[root@localhost conf]# yum -y install httpd-tools
-c 用于指定的并发数;-n 用于指定压力测试总共的执行次数
[root@localhost conf]# ab -c 100 -n 5000 http://192.168.71.134/index1.html
This is ApacheBench, Version 2.3 <$Revision: 1430300 $>
Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/
Licensed to The Apache Software Foundation, http://www.apache.org/

Benchmarking 192.168.71.134 (be patient)
Completed 500 requests
Completed 1000 requests
Completed 1500 requests
Completed 2000 requests
Completed 2500 requests
Completed 3000 requests
Completed 3500 requests
Completed 4000 requests
Completed 4500 requests
Completed 5000 requests
Finished 5000 requests


Server Software:        nginx/1.20.1
Server Hostname:        192.168.71.134
Server Port:            80

Document Path:          /index1.html
Document Length:        153 bytes

Concurrency Level:      100
Time taken for tests:   0.390 seconds
Complete requests:      5000
Failed requests:        0
Write errors:           0
Non-2xx responses:      5000
Total transferred:      1515000 bytes
HTML transferred:       765000 bytes
Requests per second:    12825.64 [#/sec] (mean)
Time per request:       7.797 [ms] (mean)
Time per request:       0.078 [ms] (mean, across all concurrent requests)
Transfer rate:          3795.09 [Kbytes/sec] received

Connection Times (ms)
              min  mean[+/-sd] median   max
Connect:        0    3   2.4      3      35
Processing:     1    5   5.3      3      49
Waiting:        0    4   4.9      3      47
Total:          3    8   6.0      6      52

Percentage of the requests served within a certain time (ms)
  50%      6
  66%      7
  75%      8
  80%      8
  90%     11
  95%     15
  98%     20
  99%     49
 100%     52 (longest request)

网络连接相关的配置参数

keepalive_timeout number;    //长连接的超时时长,默认为65s
keepalive_requests number;    //在一个长连接上所能够允许请求的最大资源数
keepalive_disable [msie6|safari|none];    //为指定类型的UserAgent禁用长连接
tcp_nodelay on|off;    //是否对长连接使用TCP_NODELAY选项,为了提升用户体验,通常设为on
client_header_timeout number;    //读取http请求报文首部的超时时长
client_body_timeout number;    //读取http请求报文body部分的超时时长
send_timeout number;    //发送响应报文的超时时长


keepalive_timeout number //65s内没做任何操作就超时退出
keepalive_requests number //连接建立之后可以设置一个值,这个值就是要处理的请求,当请求全部处理完成之后才退出
keepalive_disable [msie6|safari|none]  //disabl可以在http,server,location中配置,在什么地方配置就对哪个地方生效(也就是禁用某个浏览器的长连接),这里的msie6|safari是浏览器的类型,none就是空任何类型都可以访问

[root@localhost conf]# vim nginx.conf
34     keepalive_disable msie6;

tcp_nodelay on|off  //设置使用长连接没有延迟,默认也是no

fastcgi的相关配置参数

LNMP:php要启用fpm模型
配置示例如下:
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;
}

经常需要进行调整的参数

worker_processes
worker_connections
worker_cpu_affinity
worker_priority

nginx作为web服务器时使用的配置:http{}段的配置参数
http{…}:配置http相关,由ngx_http_core_module模块引入。nginx的HTTP配置主要包括四个区块,结构如下:
若想要配置HTTP可以到官网相关的模块进行参考
https://nginx.org/en/docs/http/ngx_http_core_module.html

http {//协议级别
  include mime.types;  
  default_type application/octet-stream;  
  keepalive_timeout 65;  
  gzip on;  
  upstream {//负载均衡配置  
    ...
  }
  server {//服务器级别,每个server类似于httpd中的一个<VirtualHost>  //这个就类似于一个网站
    listen 80;  
    server_name localhost;  
    location / {//请求级别,类似于httpd中的<Location>,用于定义URL与本地文件系统的映射关系
      root html;  
      index index.html index.htm;  
    }
  }
}


部署一个http的页面
[root@localhost test]# cat index.html 
test web
[root@localhost test]# pwd
/usr/local/nginx/html/test

[root@localhost conf]# vim nginx.conf
[root@localhost conf]# pwd
/usr/local/nginx/conf
 36     #gzip  on;
 37 
 38     server {
 39       listen 82;
 40       server_name test.example.com;
 41 
 42       location / {
 43           root html/test;
 44           index index.html;
 45       }
 46    }

检查nginx的语法
[root@localhost conf]# nginx -t
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: [warn] the number of "worker_processes" is not equal to the number of "worker_cpu_affinity" masks, using last mask for remaining worker processes
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful

重启nginx服务
[root@localhost conf]# systemctl restart nginx.service
[root@localhost conf]# ss -anlt
State       Recv-Q Send-Q Local Address:Port               Peer Address:Port              
LISTEN      0      128            *:80                         *:*                  
LISTEN      0      128            *:82                         *:*                  
LISTEN      0      128            *:22                         *:*

在这里插入图片描述

http{}段配置指令:

server {}:定义一个虚拟主机:

server {
  listen 80;
  server_name www.idfsoft.com;
  root "/vhosts/web";
}

listen:指定监听的地址和端口
listen address[:port];
listen port;
server_name NAME [...]; 后面可跟多个主机,名称可使用正则表达式或通配符
当有多个server时,匹配顺序如下:

1. 先做精确匹配检查
2. 左侧通配符匹配检查,如*.idfsoft.com
3. 右侧通配符匹配检查,如mail.*
4. 正则表达式匹配检查,如~ ^.*\.idfsoft\.com$
5. default_server
oot path;设置资源路径映射,用于指明请求的URL所对应的资源所在的文件系统上的起始路径
alias path;用于location配置段,定义路径别名
index file; 默认主页面
index index.php index.html;


为了安全可以通过root path;设置资源路径映射
server {
        listen       80;
        server_name  localhost;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

        location / {
            alias   /var/www/html/;   //alias的特点是的必须跟上绝对路径
            index  index.html index.htm;
        }

[root@localhost ~]# mkdir -p  /var/www/html/  //将test目录放在此目录下
[root@localhost html]# mv /usr/local/nginx/html/test ./
[root@localhost html]# ls
test
[root@localhost ~]# systemctl restart nginx.service

在这里插入图片描述

error_page code […] [=code] URI | @name 根据http响应状态码来指明特用的错误页面,例如 error_page 404 /404_customed.html //404表示服务端无法找到客户端想要请求的资源,响应状态码为“NOT Found”,当出现此类型的报错就会使用404_customed.html 这个文件里面的内容进行响应

[=code]:以指定的响应码进行响应,而不是默认的原来的响应,默认表示以新资源的响应码为其响应码,例如 error_page 404 =200 /404_customed.html
log_format 定义日志格式:

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;
//404页面

随便到百度里面找一个网页来替代404页面,以此来检测效果
[root@localhost conf]# vim nginx.conf
48         error_page  404              /404.html;  //取消注释
[root@localhost html]# pwd
/usr/local/nginx/html

[root@localhost html]# mv 程序员客栈-领先的程序员自由远程工作平台.html 404.html
[root@localhost html]# ls
404.html  50x.html  index.html  程序员客栈-领先的程序员自由远程工作平台_files

[root@localhost conf]# systemctl restart nginx.service

|--------------------------------------------------------------------------------------------------------|

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

//访问的状态码为404,修改配置文件可让状态码变为200
[root@localhost conf]# vim nginx.conf
 48         error_page  404 =200             /404.html;
[root@localhost conf]# systemctl restart nginx.service
[root@localhost conf]# pwd
/usr/local/nginx/conf
[root@localhost conf]# vim nginx.conf
[root@localhost conf]# systemctl restart nginx.service
 17 http {
 18     include       mime.types;
 19     default_type  application/octet-stream;
 20 
 21     log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
 22                       '$status $body_bytes_sent "$http_referer" '
 23                       '"$http_user_agent" "$http_x_forwarded_for"';
 24 
 25     access_log  logs/access.log  main;

[root@localhost logs]# pwd
/usr/local/nginx/logs
[root@localhost logs]# ls
access.log  nginx.pid
[root@localhost logs]# tail -f access.log  //查看用户访问的日志
192.168.71.1 - - [28/Oct/2021:10:45:57 +0800] "GET / HTTP/1.1" 304 0 "-" "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.81 Safari/537.36" "-"
//日志所对应的内容
$remote_addr  对应 192.168.71.1 访问的客户端是什么

$remote_user  //这个是nginx的内置变量 对应第二个 - 就是远程主机使用的哪个远程用户进行的访问

[$time_local]  对应的是 [28/Oct/2021:10:45:57 +0800]本地时间,这里时间是中国上海时间,+0800表示为东八区

$request 对应的是GET / HTTP/1.1  //GET就是请求服务器的方法,从服务器获取一个资源这个获取的资源是 "/" 为默认首页 使用http协议的版本为HTTP/1.1

$status 对应 304  //304表示的是客户端发出了条件式请求,但服务器端发现客户端请求的资源已被客户端缓存过且未发生改变,让客户端直接到缓存里去取。响应状态码为“Not Modified”

$body_bytes_sent 对应 0 //表示是放松主体的字节数,因为这里使用的是缓存,所以没有发送

$http_referer 对应 - //表示为是否跳转,因为我们是通过IP进行访问的,不是跳转是直接访问的,所以这个里显示的是-。跳转就是通过某个网站的主页,点击你想要访问的页面是跳转,而我们直接通过IP进行访问。

$http_user_agent 对应 Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.81 Safari/537.36  //表示使用的什么浏览器

$http_x_forwarded_for 对应 -  //表示从什么地方跳转过来的,因为我们使用IP进行访问没有跳转,所以显示为-
//平滑升级

步骤:
1. 获取老版本的编译参数可以使用 -V来查看
2. 获取新版本或新功能的软件包
3. 对新版本的软件包进行编译,不用安装
4. 备份老程序
5. 停止老程序并用新程序,使用老程序的配置文件进行启动
6. 检验功能,如果没有问题就替换老程序使用新程序
一、
[root@localhost opt]# nginx -V
nginx version: nginx/1.20.1
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

二、软件包可以去GitHub上下载:https://github.com/openresty/echo-nginx-module

[root@localhost local]# yum -y install unzip
[root@localhost local]# unzip echo-nginx-module-master.zip


三、
[root@localhost local]# nginx -V
nginx version: nginx/1.20.1
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

[root@localhost nginx-1.20.1]# pwd
/usr/local/nginx-1.20.1
[root@localhost local]# ls
bin                           etc      lib      nginx         share
echo-nginx-module-master      games    lib64    nginx-1.20.1  src
echo-nginx-module-master.zip  include  libexec  sbin

[root@localhost nginx-1.20.1]# ./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@localhost nginx-1.20.1]# make

[root@localhost objs]# pwd
/usr/local/nginx-1.20.1/objs

[root@localhost objs]# ls
addon         Makefile  nginx.8            ngx_auto_headers.h  ngx_modules.o
autoconf.err  nginx     ngx_auto_config.h  ngx_modules.c       src

四、
[root@localhost nginx-1.20.1]# cp /usr/local/nginx/sbin/nginx /mnt/

五、
[root@localhost nginx-1.20.1]# systemctl stop nginx.service ; objs/nginx -c /usr/local/nginx/conf/nginx.conf

[root@localhost nginx-1.20.1]# ps -ef | grep nginx
root      37757      1  0 11:13 ?        00:00:00 nginx: master process objs/nginx -c /usr/local/nginx/conf/nginx.conf
nginx     37758  37757  0 11:13 ?        00:00:00 nginx: worker process
root      38249   1203  0 11:13 pts/0    00:00:00 grep --color=auto nginx

六、
[root@localhost conf]# vim nginx.conf
 43         location /abc {
 44             echo "hello";
 45         }
检查nginx的语法
[root@localhost nginx-1.20.1]# 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.20.1]# objs/nginx -s reload
[root@localhost conf]# curl http://192.168.71.138/abc
hello

覆盖老配制文件
[root@localhost nginx-1.20.1]# cp objs/nginx /usr/local/nginx/sbin/nginx 
cp:是否覆盖"/usr/local/nginx/sbin/nginx"? y

[root@localhost nginx-1.20.1]# 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
//location区段,通过指定模式来与客户端请求的URI相匹配 //location用来定位资源的位置

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

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

常用修饰符

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

[root@localhost conf]# curl http://192.168.71.138/abc
hello
[root@localhost conf]# curl http://192.168.71.138/abc/
hello
[root@localhost conf]# curl http://192.168.71.138/abcde
hello
[root@localhost conf]# curl http://192.168.71.138/abcde/
hell
=:表示精确匹配

[root@localhost conf]# vim nginx.conf
48         location = /abc {
 49             echo "hello";
 50         }
显示的内容如下:

就是只要前三个字符包含abc就可以输出hello,但是abc后面不能跟类似于"<  >   | "等具有特殊意义的字符
[root@localhost conf]# curl http://192.168.71.138/abcDB
hello
[root@localhost conf]# curl http://192.168.71.138/abCdb
<html>
<head><title>404 Not Found</title></head>
<body>
<center><h1>404 Not Found</h1></center>
<hr><center>nginx/1.20.1</center>
</body>
</html>
~:表示指定的正则表达式要区分大小写:

[root@localhost conf]# vim nginx.conf
location ~ ^/abc$ {
            echo "hello";
        }
[root@localhost conf]# nginx -s reload
显示如下内容:

表示的是/abc这个目录下的内容/abc/表示/abc下一级目录的内容,且要以/abc开头和结尾
[root@localhost conf]# curl http://192.168.71.138/abc
hello
[root@localhost conf]# curl http://192.168.71.138/abc?jjyy
hello

[root@localhost conf]# curl http://192.168.71.138/abcu
<html>
<head><title>404 Not Found</title></head>
<body>
<center><h1>404 Not Found</h1></center>
<hr><center>nginx/1.20.1</center>
</body>
</html>

[root@localhost conf]# curl http://192.168.71.138/abc/
<html>
<head><title>404 Not Found</title></head>
<body>
<center><h1>404 Not Found</h1></center>
<hr><center>nginx/1.20.1</center>
</body>
</html>
~*:表示指定的正则表达式不区分大小写


[root@localhost conf]# vim nginx.conf
       location ~* ^/abc$ {
            echo "hello";
        }
[root@localhost conf]# nginx -s reload
显示如下:


和上面的类似,只是这个不区分大小写
[root@localhost conf]# curl http://192.168.182.131/ABC
hello
[root@localhost conf]# curl http://192.168.182.131/ABCd
<html>
<head><title>404 Not Found</title></head>
<body>
<center><h1>404 Not Found</h1></center>
<hr><center>nginx/1.20.1</center>
</body>
</html>
[root@localhost conf]# curl http://192.168.71.138/ABC/
<html>
<head><title>404 Not Found</title></head>
<body>
<center><h1>404 Not Found</h1></center>
<hr><center>nginx/1.20.1</center>
</body>
</html>

[root@localhost conf]# curl http://192.168.182.131/ABCjjyy
<html>
<head><title>404 Not Found</title></head>
<body>
<center><h1>404 Not Found</h1></center>
<hr><center>nginx/1.20.1</center>
</body>
</html>

~:类似于无修饰符的行为,也是以指定模式开始,不同的是,如果模式匹配,则停止搜索其他模式
查找顺序和优先级:由高到底依次为:

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

//优先级次序如下:
( location = 路径 ) --> ( location ^~ 路径 ) --> ( location ~ 正则 ) --> ( location ~* 正则 ) --> ( location 路径 )

访问控制

用于location段
allow:设定允许哪台或哪些主机访问,多个参数间用空格隔开
deny:设定禁止哪台
案例:

就是除了130和131这两个IP其余的IP都可以访问
location /  {
       deny  192.168.71.134;
       deny   192.168.71.138;
       allow 192.168.71.0;
}

[root@localhost html]# mkdir test
[root@localhost html]# cd test/
[root@localhost test]# vim index.html
[root@localhost test]# cat index.html
<html>
<head>
<title>test web</title>
</head>
<a href="http://www.baidu.com">baidu</a>
</body>
</html>

[root@localhost conf]# vim nginx.conf
location /test {
            root html;
            index  index.html;
[root@localhost conf]# nginx -s reload

在这里插入图片描述

[root@localhost conf]# vim nginx.conf
        location /test {
            deny  192.168.71.1;
            root html;
            index  index.html;
        }

[root@localhost conf]# nginx -s reload

在这里插入图片描述

让除192.168.71.1之外的网段都无法访问
[root@localhost conf]# vim nginx.conf
location /test {
            allow  192.168.71.1;
            deny   all;
            root html;
            index  index.html;
        }
[root@localhost conf]# nginx -s reload

在这里插入图片描述

//本地无法访问
[root@localhost test]# curl http://192.168.71.138/test/index.html
<html>
<head><title>403 Forbidden</title></head>
<body>
<center><h1>403 Forbidden</h1></center>
<hr><center>nginx/1.20.1</center>
</body>
</html>

在这里插入图片描述

基于用户认证

//语法、使用位置

Syntax: 	auth_basic string | off;  语法
Default: 	auth_basic off;   //默认关闭
Context: 	http, server, location, limit_except   //使用位置

//user_auth_file内容格式为:
username:passw![or](https://img-blog.csdnimg.cn/f0308bfb1bb64e04b69a19207b50afcb.png?x-oss-process=image/watermark,type_ZHJvaWRzYW5zZmFsbGJhY2s,shadow_50,text_Q1NETiBAbHgtLXl0,size_20,color_FFFFFF,t_70,g_se,x_16)
d

//这里的密码为加密后的密码串,建议用htpasswd来创建此文件:
htpasswd -c -m /path/to/.user_auth_file USERNAME

基于用户认证测试

密码放置位置

//使用htpasswd命令生成密码,若没有htpasswd命令。yum安装httpd-tools包即可
[root@localhost conf]# htpasswd -c -m .pass admin
New password: 
Re-type new password: 
Adding password for user admin
[root@localhost conf]# cat .pass 
admin:$apr1$vPWj84D5$vmhK9FW3zl3mEAa/VkRNL0    //生成的密码以加密的方式存放

修改配置文件

[root@localhost ~]# vim /usr/local/nginx/conf/nginx.conf
......
        location /test {
            auth_basic "欢迎光临";     
            auth_basic_user_file ".pass";      //因为密码文件和配置文件同级目录,所以可以直接写相对路径
            root   html;
            index  index.html;
        }
......
[root@localhost ~]# nginx -s reload   //重新加载配置文件

https配置

生成证书

[root@localhost ~]# mkdir -p /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
..........................................................................................................................................+++
.........................................+++
e is 65537 (0x10001)

生成自签署证书
[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]:runtime
Organizational Unit Name (eg, section) []:runtime
Common Name (eg, your name or your server's hostname) []:test.runtime.com
Email Address []:1@2.com
[root@localhost CA]# mkdir certs newcerts crl
[root@localhost CA]# touch index.txt && echo 01 > serial

创建证书存放位置
[root@localhost ~]# mkdir /usr/local/nginx/conf/ssl
[root@localhost ssl]# pwd
/usr/local/nginx/conf/ssl

[root@localhost ssl]# (umask 077;openssl genrsa -out nginx.key 2048)
Generating RSA private key, 2048 bit long modulus
.......+++
.............................+++
e is 65537 (0x10001)



//生成证书签署请求
[root@localhost ssl]# openssl req -new -key nginx.key -days 365 -out nginx.csr
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]:runtime
Organizational Unit Name (eg, section) []:runtime
Common Name (eg, your name or your server's hostname) []:test.runtime.com
Email Address []:1@2.com

Please enter the following 'extra' attributes
to be sent with your certificate request
A challenge password []:
An optional company name []:

[root@localhost ssl]# ls
nginx.csr  nginx.key


//修改nginx配置文件
104     server {
105         listen       443 ssl;
106         server_name  localhost;
107 
108         ssl_certificate      ssl/nginx.pem;  //修改此行
109         ssl_certificate_key  ssl/nginx.key;  //修改此行
110 
111         ssl_session_cache    shared:SSL:1m;
112         ssl_session_timeout  5m;
113 
114         ssl_ciphers  HIGH:!aNULL:!MD5;
115         ssl_prefer_server_ciphers  on;
116 
117         location / {
118             root   html;
119             index  index.html index.htm;
120         }
121     }


//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 12:22:40 2021 GMT
            Not After : Oct 28 12:22:40 2022 GMT
        Subject:
            countryName               = CN
            stateOrProvinceName       = HB
            organizationName          = runtime
            organizationalUnitName    = runtime
            commonName                = test.runtime.com
            emailAddress              = 1@2.com
        X509v3 extensions:
            X509v3 Basic Constraints: 
                CA:FALSE
            Netscape Comment: 
                OpenSSL Generated Certificate
            X509v3 Subject Key Identifier: 
                D7:98:3F:0B:01:1F:C2:5D:90:66:91:8C:81:BA:B8:EF:DE:78:6D:13
            X509v3 Authority Key Identifier: 
                keyid:D9:7E:A3:67:BB:F5:DA:BC:6B:A7:A6:47:54:33:0E:7A:60:03:95:71

Certificate is to be certified until Oct 28 12:22:40 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]# nginx -s quit;nginx

在这里插入图片描述

状态界面

//开启状态界面
[root@localhost ~]# vim /usr/local/nginx/conf/nginx.conf

       location /status {
            stub_status on;
            allow 192.168.71.1/24;
            deny all;
        }
[root@localhost ~]# nginx -s stop;nginx

访问状态页面的方式:http://server_ip/status

状态页面信息详解:

状态码表示的意义
Active connections 2当前所有处于打开状态的连接数
accepts总共处理了多少个连接
handled成功创建多少握手
requests总共处理了多少个请求
Readingnginx读取到客户端的Header信息数,表示正处于接收请求状态的连接数
Writing nginx返回给客户端的Header信息数,表示请求已经接收完成,且正处于处理请求或发送响应的过程中的连接数
Waiting开启keep-alive的情况下,这个值等于active - (reading + writing),意思就是Nginx已处理完正在等候下一次请求指令的驻留连接

在这里插入图片描述
在这里插入图片描述

状态界面监控

zabbix客户端安装

//关闭防火墙和selinux
//创建用户
[root@localhost ~]# useradd -r -M -s /sbin/nologin zabbix

//安装依赖包
[root@localhost ~]# yum -y install wget vim gcc gcc-c++ make pcre-devel openssl openssl-devel

//下载并解压zabbix
[root@localhost ~]# cd /usr/src/
[root@localhost src]# ls
debug  kernels  nginx-1.20.1  zabbix-5.4.4.tar.gz
[root@localhost src]# tar xf zabbix-5.4.4.tar.gz 
[root@localhost src]# cd zabbix-5.4.4/
[root@localhost zabbix-5.4.4]# ls
aclocal.m4  ChangeLog     config.sub    database  install-sh   man      README
AUTHORS     compile       configure     depcomp   m4           misc     sass
bin         conf          configure.ac  include   Makefile.am  missing  src
build       config.guess  COPYING       INSTALL   Makefile.in  NEWS     ui

//编译安装
[root@localhost zabbix-5.4.4]# ./configure --enable-agent
......
***********************************************************
*            Now run 'make install'                       *
*                                                         *
*            Thank you for using Zabbix!                  *
*              <http://www.zabbix.com>                    *
***********************************************************

[root@localhost zabbix-5.4.4]# make install

//修改配置文件
[root@localhost ~]# cd /usr/local/etc/
[root@localhost etc]# ls
zabbix_agentd.conf  zabbix_agentd.conf.d
[root@localhost etc]# vim zabbix_agentd.conf
113 Server=192.168.71.134		//指定zabbix服务端IP
154 ServerActive=192.168.71.134	//指定zabbix服务端IP
165 Hostname=nginx		//指定主机名,zabbix web界面添加主机时的需要填写的主机名

//开机自启
[root@localhost ~]# cp /usr/src/zabbix-5.4.4/misc/init.d/fedora/core/zabbix_agentd /etc/init.d/
[root@agent ~]# cat /usr/lib/systemd/system/zabbix_agentd.service 
[Unit]
Description=zabbix server daemon
After=network.target

[Service]
Type=forking
ExecStart=/etc/init.d/zabbix_agentd start
ExecStop=/etc/init.d/zabbix_agentd stop
ExecReload=/bin/kill -HUP $MAINPID

[Install]
WantedBy=multi-user.target

[root@agent ~]# systemctl daemon-reload 
[root@localhost ~]# systemctl enable --now zabbix_agentd
Synchronizing state of zabbix_agentd.service with SysV service script with /usr/lib/systemd/systemd-sysv-install.
Executing: /usr/lib/systemd/systemd-sysv-install enable zabbix_agentd
[root@localhost ~]# ss -anltu
Netid      State       Recv-Q      Send-Q           Local Address:Port            Peer Address:Port     
tcp        LISTEN      0           128                    0.0.0.0:80                   0.0.0.0:*        
tcp        LISTEN      0           128                    0.0.0.0:22                   0.0.0.0:*        
tcp        LISTEN      0           128                    0.0.0.0:10050                0.0.0.0:*        
tcp        LISTEN      0           128                       [::]:22                      [::]:*        

//编写脚本
脚本位置不要放在/root目录下,zabbix用户无法进入/root目录
[root@localhost ~]# cat /opt/scripts/get_nginx_status.sh 
#!/bin/bash
NGINX_SERVER=192.168.71.138
NGINX_URL="http://${NGINX_SERVER}/status"

function get_active() {     
        curl -s ${NGINX_URL} | grep "Active" | awk -F ":" '{print $2}'
} 
function get_reading() {     
        curl -s ${NGINX_URL} | grep "Reading" | awk -F ":" '{print $2}' | awk -F " " '{print $1}'
} 
function get_writing() {     
        curl -s ${NGINX_URL} | grep "Writing" | awk -F ":" '{print $3}' | awk -F " " '{print $1}'
} 
function get_waiting() {     
        curl -s ${NGINX_URL} | grep "Waiting" | awk -F ":" '{print $4}' | awk -F " " '{print $1}'
} 
function get_accepts() {     
        curl -s ${NGINX_URL} | awk NR==3 | awk -F " " '{print $1}'
} 
function get_handled() {     
        curl -s ${NGINX_URL} | awk NR==3 | awk -F " " '{print $2}'
} 
function get_requests() {     
        curl -s ${NGINX_URL} | awk NR==3 | awk -F " " '{print $3}'
}

case $1 in      
active)          
    get_active          
    ;;     
reading)          
    get_reading          
    ;;     
writing)          
    get_writing              
    ;;     
waiting)          
    get_waiting          
    ;;     
accepts)          
    get_accepts           
    ;;     
handled)          
    get_handled          
    ;;     
requests)          
    get_requests              
    ;;     
*)         
    echo "Usage: $0 {active | reading | writing | waiting | accepts | handled | requests}"
esac
//修改配置文件,加入脚本位置,让zabbix能执行脚本

[root@localhost ~]# tail -8 /usr/local/etc/zabbix_agentd.conf
UnsafeUserParameters=1
UserParameter=nginx.active, /opt/scripts/get_nginx_status.sh active
UserParameter=nginx.reading, /opt/scripts/get_nginx_status.sh reading
UserParameter=nginx.writing, /opt/scripts/get_nginx_status.sh writing
UserParameter=nginx.waiting, /opt/scripts/get_nginx_status.sh waiting
UserParameter=nginx.accepts, /opt/scripts/get_nginx_status.sh accepts
UserParameter=nginx.handled, /opt/scripts/get_nginx_status.sh handled
UserParameter=nginx.requests, /opt/scripts/get_nginx_status.sh requests

//重启zabbix客户端
[root@localhost ~]# systemctl restart zabbix_agentd.service 

zabbix监控端测试

//能够成功执行客户端脚本,并取到对应值
[root@zabbix ~]# zabbix_get -s 192.168.71.138 -k nginx.accepts
25
[root@zabbix ~]# zabbix_get -s 192.168.71.138 -k nginx.accepts
26
[root@zabbix ~]# zabbix_get -s 192.168.71.138 -k nginx.waiting
0
[root@zabbix ~]# zabbix_get -s 192.168.71.138 -k nginx.writing
1
[root@zabbix ~]# zabbix_get -s 192.168.71.138 -k nginx.reading
0

web界面

在这里插入图片描述

在这里插入图片描述

rewrite

语法:rewrite regex replacement flag;,如:

//所有访问/images目录下的jpg文件的请求都重定向到/imgs目录下jpg文件来响应
rewrite ^/images/(..jpg)$ /imgs/$1 break; //此处的$1用于引用(..jpg)匹配到的内容

//所有访问/bbs目录下的文件的请求都重定向到http://www.idfsoft.com/index.html这个网页来响应
rewrite ^/bbs/(.*)$ http://www.idfsoft.com/index.html redirect;

replacement可以是某个路径,也可以是某个URL

常见的flag

flag作用
last基本上都用这个flag,表示当前的匹配结束,继续下一个匹配,最多匹配10个到20个一旦此rewrite规则重写完成后,就不再被后面其它的rewrite规则进行处理而是由UserAgent重新对重写后的URL再一次发起请求,并从头开始执行类似的过程
break中止Rewrite,不再继续匹配一旦此rewrite规则重写完成后,由UserAgent对新的URL重新发起请求,且不再会被当前location内的任何rewrite规则所检查
redirect以临时重定向的HTTP状态302返回新的URL
permanent以永久重定向的HTTP状态301返回新的URL

rewrite模块的作用是用来执行URL重定向。这个机制有利于去掉恶意访问的url,也有利于搜索引擎优化(SEO)

nginx使用的语法源于Perl兼容正则表达式(PCRE)库,基本语法如下:

标识符意义
^必须以^后的实体开头
$必须以$前的实体结尾
.匹配任意字符
[]匹配指定字符集内的任意字符
[^]匹配任何不包括在指定字符集内的任意字符串
匹配 之前或之后的实体
()分组,组成一组用于匹配的实体,通常会有

捕获子表达式,可以捕获放在()之间的任何文本,比如:

^(hello|sir)$ //字符串为“hi sir”捕获的结果:$1=hi$2=sir

//这些被捕获的数据,在后面就可以当变量一样使用了

案例
重定向到本地资源

//在html目录下创建一个目录存放一个jpg文件
[root@localhost html]# pwd
/usr/local/nginx/html
[root@localhost html]# mkdir images
[root@localhost images]# ls
1.jpg

在这里插入图片描述
在这里插入图片描述

//修改images目录名称为imgs
[root@localhost html]# mv images/ imgs
[root@localhost html]# ls
50x.html  imgs  index.html
[root@localhost html]# ls imgs/
1.jpg

在这里插入图片描述

重定向

[root@localhost ~]# vim /usr/local/nginx/conf/nginx.conf
 48         location /images {
 49             rewrite ^/images/(.*\.jpg)$ /imgs/$1 break;		//访问images/下的jpg文件重定向到imgs/下的jpg文件响应
 50         }
[root@localhost ~]# nginx -s stop;nginx

在这里插入图片描述

在这里插入图片描述

//重定向到网络资源

[root@localhost ~]# vim /usr/local/nginx/conf/nginx.conf
 48         location /images {
 49             rewrite ^/images/(.*\.jpg)$ http://www.itwangqing.net.cn/15347293082090.html#toc_28 break;  	//将重定向到本地资源路径改为网络资源的URL
 50         }
[root@localhost ~]# nginx -s stop;nginx

if

语法:if (condition) {…}

应用场景:

server段
location段

常见的condition

变量名(变量值为空串,或者以“0”开始,则为false,其它的均为true)
以变量为操作数构成的比较表达式(可使用=,!=类似的比较操作符进行测试)
正则表达式的模式匹配操作
~:区分大小写的模式匹配检查
~:不区分大小写的模式匹配检查
!和!
:对上面两种测试取反
测试指定路径为文件的可能性(-f,!-f)
测试指定路径为目录的可能性(-d,!-d)
测试文件的存在性(-e,!-e)
检查文件是否有执行权限(-x,!-x)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值