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

就是worker进程最多能打开1024个文件数,最好将值调整至65535最大的值。这个值是因为端口号最多只有65535
这个在nginx的配置文件默认没有,这需要我们自己手动添加
[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

worker_rlimit_core size; //指明所有worker进程所能够使用的总体的最大核心文件大小,保持默认即可这个东西很少使用

优化性能的配置参数

这个是用来优化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进程使用,剩余的给其他系统服务使用。

worker_cpu_affinity cpumask ...; //将进程绑定到某cpu中,避免频繁刷新缓存

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

user  nginx nginx;
worker_processes  1;
worker_cpu_affinity 0001 0010

然后使用top命令,再点击L键,输入nginx就可以找到nginx的进程
top - 19: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                                              0

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 20:05 ?        00:00:00 nginx: master process /usr/local/nginx/sbin/nginx
5 S nginx     11243  11242  0  60 -20 - 19435 ep_pol 20:05 ?        00:00:00 nginx: worker process
0 S root      16510   2288  0  80   0 - 28206 pipe_w 20: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.182.131/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.182.131 (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.182.131
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

root 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;

//注意:此处可用变量为nginx各模块内建变量

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.182.1 - - [27/Oct/2021:18: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.182.1 访问的客户端是什么

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

[$time_local]  对应的是 [27/Oct/2021:18: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 21:13 ?        00:00:00 nginx: master process objs/nginx -c /usr/local/nginx/conf/nginx.conf
nginx     37758  37757  0 21:13 ?        00:00:00 nginx: worker process
root      38249   1203  0 21: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.182.131/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.182.131/abc
hello
[root@localhost conf]# curl http://192.168.182.131/abc/
hello
[root@localhost conf]# curl http://192.168.182.131/abcde
hello
[root@localhost conf]# curl http://192.168.182.131/abcde/
hello

=:表示精确匹配

[root@localhost conf]# vim nginx.conf
48         location = /abc {
 49             echo "hello";
 50         }

显示的内容如下:

就是只要前三个字符包含abc就可以输出hello,但是abc后面不能跟类似于"<  >   | "等具有特殊意义的字符
[root@localhost conf]# curl http://192.168.182.131/abcDB
hello
[root@localhost conf]# curl http://192.168.182.131/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.182.131/abc
hello
[root@localhost conf]# curl http://192.168.182.131/abc?jjyy
hello

[root@localhost conf]# curl http://192.168.182.131/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.182.131/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.182.131/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>

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

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

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

优先级次序如下:

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

访问控制

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

就是除了130和131这两个IP其余的IP都可以访问
location /  {
       deny  192.168.182.130;
       deny   192.168.182.131;
       allow 192.168.182.0;
}
[root@localhost test]# pwd
/usr/local/nginx/html/test

[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.182.1;
            root html;
            index  index.html;
        }

[root@localhost conf]# nginx -s reload

本地访问

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

让192.168.182.1网段可以访问

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

让除192.168.182.1之外的网段都无法访问

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

本地无法访问

[root@localhost test]# curl http://192.168.182.131/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>

基于用户认证

auth_basic "欢迎信息";
auth_basic_user_file "/path/to/user_auth_file"

user_auth_file内容格式为:

username:password

这里的密码为加密后的密码串,建议用htpasswd来创建此文件:

htpasswd -c -m /path/to/.user_auth_file USERNAME
[root@localhost conf]# yum -y install httpd-tools
[root@localhost conf]# which htpasswd 
/usr/bin/htpasswd

[root@localhost conf]# pwd
/usr/local/nginx/conf
[root@localhost conf]# touch .pass 
[root@localhost conf]# htpasswd -c -m .pass admin 
New password: 
Re-type new password: 
Adding password for user admin

[root@localhost conf]# vim nginx.conf
        location /test {
            auth_basic "hello world";
            auth_basic_user_file ".pass";
            root html;
            index  index.html;
       }
[root@localhost conf]# 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.crt;  //修改此行
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 03:22:40 2021 GMT
            Not After : Oct 28 03: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 03: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

开启状态界面

开启status:

location /status {
  stub_status {on | off};
  allow 172.16.0.0/16;
  deny all;
}

web页面访问的方式:http://server_ip/status
状态页面信息详解:

状态码 表示的意义
Active connections 2 当前所有处于打开状态的连接数
accepts 总共处理了多少个连接
handled 成功创建多少握手
requests 总共处理了多少个请求
Reading nginx读取到客户端的Header信息数,表示正处于接收请求状态的连接数
Writing nginx返回给客户端的Header信息数,表示请求已经接收完成,

且正处于处理请求或发送响应的过程中的连接数
Waiting | 开启keep-alive的情况下,这个值等于active - (reading + writing),
意思就是Nginx已处理完正在等候下一次请求指令的驻留连接

配置文件的配置
[root@localhost conf]# vim nginx.conf
location /status {
            stub_status on ;  //开启状态页面,off位关闭
        }
[root@localhost conf]# nginx -s reload

环境说明:

系统 IP 服务
Redhat8 192.168.182.131 zabbix_agent+nginx
redhat8 192.168.182.142 zabbix_server zabbix_agent

修改代理端的配置文件

[root@localhost scripts]# vim /usr/local/etc/zabbix_agentd.conf
UnsafeUserParameters=1
UserParameter=Waiting,/scripts/Waiting.sh

重启服务

[root@localhost ~]# pkill zabbix_agentd 
[root@localhost ~]# zabbix_agentd

编写脚本

[root@localhost scripts]# pwd
/scripts
[root@localhost scripts]# cat Waiting.sh 
#!/bin/bash
change=$(curl -s http://192.168.182.131/status | awk 'NR==4 {print $6}')
if [ $change -gt 0 ];then
     echo "1"
else
     echo "0"
fi

在服务端测试是否有问题

[root@localhost ~]# zabbix_get -s 192.168.182.131 -k Waiting
0

模拟故障

[root@localhost scripts]# curl -s http://192.168.182.131/status
Active connections: 5 
server accepts handled requests
 28 28 26 
Reading: 0 Writing: 1 Waiting: 4

[root@localhost ~]# zabbix_get -s 192.168.182.131 -k Waiting
1

创建主机组


创建主机并添加到主机组


创建监控项


查看最新数据


添加触发器


手动触发并验证
多次访问192.168.182.131:/status

[root@localhost scripts]# curl -s 192.168.182.131/status
Active connections: 3 
server accepts handled requests
 106 106 96 
Reading: 0 Writing: 1 Waiting: 2 

监控Reading、Writing脚本

若想监控其他的状态可以使用以下脚本
[root@localhost scripts]# cat Reading.sh 
#!/bin/bash
sum=$(curl -s http://192.168.182.131/status | awk 'NR==4 {print $2}')
if [ $sum -eq 0 ];then
    echo "1"
else
    echo "0"
fi

[root@localhost scripts]# cat Writing.sh 
#!/bin/bash
Writing=$(curl -s http://192.168.182.131/status | awk 'NR==4 {print $4}')
if [ $Writing -eq 0 ];then
    echo "1"
else
    echo "0"
fi

rewrite

语法:rewrite regex replacement flag;如下:

rewrite ^/images/(.*\.jpg)$ /imgs/$1 break
此处的$1用于引用(.*.jpg)匹配到的内容,又如:
rewrite ^/bbs/(.*)$ http://www.idfsoft.com/index.html redirect;
[root@localhost images]# pwd
/usr/local/nginx/html/images
[root@localhost html]# ls | grep 1
1.jpg

输入IP加路径即可访问


修改目录名

[root@localhost html]# mv images imgs

匹配以/images开头里面任意东西.jpg结尾的在/imgs/下找

[root@localhost ~]# vim /usr/local/nginx/conf/nginx.conf
        location /images {
            rewrite ^/images/(.*\.jpg)$ /imgs/$1 break;
}
[root@localhost ~]# nginx -s reload

此处的$1用于引用(.*.jpg)匹配到的内容,又如:

[root@localhost ~]# vim /usr/local/nginx/conf/nginx.conf
location /images {
            rewrite ^/images/(.*\.jpg)$ http://images.baidu.com break;
        }

[root@localhost ~]# nginx -s reload

last用法


location /images {
           rewrite ^/images/(.*\.jpg)$ /imgs/$1 last;
        }

        location /imgs {
           rewrite ^/imgs/(.*\.jpg)$ http://images.baidu.com last;
        }
[root@localhost ~]# nginx -s reload
[root@localhost ~]# vim /usr/local/nginx/conf/nginx.conf
 location /images {
           rewrite ^/images/(.*\.jpg)$ /imgs/$1 break;
        }

        location /imgs {
           rewrite ^/imgs/(.*\.jpg)$ http://images.baidu.com last;
        }
[root@localhost ~]# nginx -s reload

常见的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

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

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

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

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

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

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

if语句

语法:if (condition) {...}
应用场景:

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

基于浏览器实现分离案例

if ($http_user_agent ~ Firefox) {
  rewrite ^(.*)$ /firefox/$1 break;
}

if ($http_user_agent ~ MSIE) {
  rewrite ^(.*)$ /msie/$1 break;
}

if ($http_user_agent ~ Chrome) {
  rewrite ^(.*)$ /chrome/$1 break;
}

防盗链案例

location ~* \.(jpg|gif|jpeg|png)$ {
  valid_referers none blocked www.idfsoft.com;
  if ($invalid_referer) {
    rewrite ^/ http://www.idfsoft.com/403.html;
  }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 200,045评论 5 468
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 84,114评论 2 377
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 147,120评论 0 332
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 53,902评论 1 272
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 62,828评论 5 360
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,132评论 1 277
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,590评论 3 390
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,258评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,408评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,335评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,385评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,068评论 3 315
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,660评论 3 303
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,747评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,967评论 1 255
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,406评论 2 346
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 41,970评论 2 341

推荐阅读更多精彩内容