Nginx 配置文件详解 (初级功能)

1,126 阅读24分钟

Nginx的配置文件的组成部分:

  • 主配置文件:nginx.conf
  • 子配置文件:include conf.d/*.conf
nginx配置.png

一、 main全局块(全局设置)

从配置文件开始到 events 块之间的内容,主要会设置一些影响nginx 服务器整体运行的配置指令,主要包括配置运行 Nginx 服务器的用户(组)、允许生成的 worker process 数,进程 PID 存放路径、日志存放路径和类型以及配置文件的引入等。作用域是全局的。

1. 关闭版本或修改版本

[root@node1 ~]#  curl -I http://192.168.204.10/
HTTP/1.1 200 OK
Server: nginx/1.18.0
..............

[root@node1 ~]#  vim /apps/nginx/conf/nginx.conf   //修改配置信息
  http {                    //http语句块中进行修改
      server_tokens  off;   //关闭版本

[root@node1 ~]#  nginx -s reload    //重新加载
[root@node1 ~]#  curl -I http://192.168.204.10/   //验证
HTTP/1.1 200 OK
Server: nginx   //未显示具体版本
..............
`注意:`这是唯一一个调优是在http 语句块的,其他都在全局

2. 修改启动的进程数

worker_processes  1;   
#系统默认允许的启动工作进程数数量,和你真实的cpu数量有关

worker_processes auto;
#如果设置为auto,是你真实的cpu数量
[root@node1 ~]#  ps axo pid,cmd,psr,ni|grep nginx   //查看nginx的worker数量
 64705 nginx: master process /apps   1   0
 64837 nginx: worker process         1   0
 64948 grep --color=auto nginx       0   0

[root@node1 ~]#  vim /apps/nginx/conf/nginx.conf   //修改配置文件
  worker_processes auto;   //设置为auto就是你真实的cpu数量

[root@node1 ~]#  nginx -s reload      //重新加载
[root@node1 ~]#  ps axo pid,cmd,psr,ni|grep nginx  //再次查看nginx的worker数量
 64705 nginx: master process /apps   1   0
 64965 nginx: worker process         2   0
 64966 nginx: worker process         3   0
 64967 nginx: worker process         1   0
 64968 nginx: worker process         1   0
 64971 grep --color=auto nginx       1   0

3. cpu与work进程绑定

将Nginx工作进程绑定到指定的CPU核心,默认Nginx是不进行进程绑定的,绑定并不是意味着当前nginx进程独占一个核心CPU,但是可以保证此进程不会运行在其他核心上,这就极大减少了nginx的工作进程在不同的cpu核心上的来回跳转,减少了CPU对进程的资源分配与回收以及内存管理等,因此可以有效的提升nginx服务器的性能。

CPU序号:
CPU MASK: 000000010CPU
          000000101CPU
          ................
          100000007CPU

worker_cpu_affinity 00000001 00000010 00000100 00001000;  
//序号绑定cpu亲缘性, 第0号---第3号CPU 
`将nginx进程和cpu进行一一对应绑定`

验证cpu乱跑可以刷新网页即可
[root@node2 ~]#  while true ;do ab -c 1000 -n 1000 http://192.168.204.10/;done

[root@node1 ~]#  ps axo pid,cmd,psr|grep nginx   //pid进程号;cmd进程命令;psr进程的cpu编号
 79031 nginx: master process /apps   0
 88470 nginx: worker process         1
 88471 nginx: worker process         3
 88472 nginx: worker process         1
 88473 nginx: worker process         3
 89058 grep --color=auto nginx       3
[root@node1 ~]#  ps axo pid,cmd,psr|grep nginx
 79031 nginx: master process /apps   0
 88470 nginx: worker process         3
 88471 nginx: worker process         2
 88472 nginx: worker process         3
 88473 nginx: worker process         0
 89074 grep --color=auto nginx       3

编辑配置文件,将nginx进程与cpu进行绑定
[root@node1 ~]#  vim /apps/nginx/conf/nginx.conf
 #user  nobody;
 worker_processes  auto;
 worker_cpu_affinity 00000001 00000010 00000100 00001000;
[root@node1 ~]#  nginx -s reload    //重启服务

[root@node1 ~]#  vim /apps/ps axo pid,cmd,psr|grep nginx   //再次验证,进程与cpu绑定成功
 79031 nginx: master process /apps   0 
 89134 nginx: worker process         0
 89135 nginx: worker process         1
 89136 nginx: worker process         2
 89137 nginx: worker process         3
 89139 grep --color=auto nginx       1
[root@node1 ~]#  ps axo pid,cmd,psr|grep nginx
 79031 nginx: master process /apps   0
 89134 nginx: worker process         0
 89135 nginx: worker process         1
 89136 nginx: worker process         2
 89137 nginx: worker process         3
 89141 grep --color=auto nginx       1

4. nginx进程的优先级

当你想将nginx的work进程的优先级调高,可以使用nice设置。

worker_priority 0; 
//工作进程优先级,-20~20(19)
`进程的默认优先级是0`
[root@node1 ~]#  ps axo pid,cmd,psr,ni|grep nginx
 79031 nginx: master process /apps   0   0
 89134 nginx: worker process         0   0
 89135 nginx: worker process         1   0
 89136 nginx: worker process         2   0
 89137 nginx: worker process         3   0
 89318 grep --color=auto nginx       3   0

编辑配置文件,设置优先级
[root@node1 ~]#  vim /apps/nginx/conf/nginx.conf
 #user  nobody;
 worker_processes  auto;
 worker_cpu_affinity 00000001 00000010 00000100 00001000;
 worker_priority -20;  //设置优先级,-20的优先级最高
[root@node1 ~]#  nginx -s reload  //重新加载

[root@node1 ~]#  ps axo pid,cmd,psr,ni|grep nginx   //ni优先级
 79031 nginx: master process /apps   1   0
 89351 nginx: worker process         0 -20
 89352 nginx: worker process         1 -20
 89353 nginx: worker process         2 -20
 89354 nginx: worker process         3 -20
 89356 grep --color=auto nginx       0   0

5. 调试work进程打开的文件的个数 ★★★

nginx 默认所有子进程一共可以打开的文件数量有限,所以需要优化数值。

worker_rlimit_nofile 65536; 
//所有worker进程能打开的文件数量上限,包括:Nginx的所有连接(例如与代理服务器的连接等),而不仅仅是与客户端的连接,另一个考虑因素是实际的并发连接数不能超过系统级别的最大打开文件数的限制。
//最好与ulimit -n 或者limits.conf的值保持一致。
`修改nginx配置文件`
[root@node1 ~]#  vim /apps/nginx/conf/nginx.conf
 #user  nobody;
 worker_processes  auto;
 worker_cpu_affinity 00000001 00000010 00000100 00001000;
 worker_priority -20;
 worker_rlimit_nofile 65536;      //修改worker进程能打开的文件数量
[root@node1 ~]#  nginx -s reload  //重新加载

[root@node1 ~]#  ulimit -a        //显示当前的各种用户进程限制
.................
open files                      (-n) 1024

`修改系统默认项`
[root@node1 ~]#  vim /etc/security/limits.conf   //修改pam认证文件
 #<domain>      <type>  <item>         <value>
 *                soft    core            unlimited
 *                hard    core            unlimited
 *                soft    nproc           1000000
 *                hard    nproc           1000000
 *                soft    nofile          1000000
 *                hard    nofile          1000000
 *                soft    memlock         32000
 *                hard    memlock         32000
 *                soft    msgqueue        8192000
 *                hard    msgqueue        8192000

修改完成后重启客户机
[root@node1 ~]#  ulimit -a   //显示当前的各种用户进程限制
...............
open files                      (-n) 1000000

注意:nginx和系统都需要设置打开文件的数量!!!\color{red}{注意:nginx 和 系统 都需要设置打开文件的数量!!!}

6. 服务是否以后台方式运行

一般服务都是后台运行;容器中需要前台运行。

daemon off;    //添加此选项

二、 events块(nginx工作模式)

events 块涉及的指令主要影响 Nginx 服务器与用户的网络连接,常用的设置包括是否开启对多 work process 下的网络连接进行序列化,是否允许同时接收多个网络连接,选取哪种事件驱动模型来处理连接请求,每个 work process 可以同时支持的最大连接数等。

`events  I/O模型调优`

events {
   worker_connections  65536;  //设置单个工作进程的最大并发连接数
   use epoll;
   //使用epoll事件驱动,Nginx支持众多的事件驱动,比如:select、poll、epoll,只能设置在events模块中设置。
   accept_mutex on; 
   //on为同一时刻一个请求轮流由work进程处理,而防止被同时唤醒所有worker,避免多个睡眠进程被唤醒的设置,默认为off,新请求会唤醒所有worker进程,此过程也称为"惊群",因此nginx刚安装完以后要进行适当的优化。建议设置为on
   multi_accept on; 
   //ON时Nginx服务器的每个工作进程可以同时接受多个新的网络连接,此指令默认为off,即默认为一个工作进程只能一次接受一个新的网络连接,打开后几个同时接受多个。建议设置为on
}

三、 http块(http设置)

http 是一个大的语句块,包含若干个小的语句块(比如server语句块)

1. server块(主机设置)

  • 一个server就是一个虚拟主机
  • server作用:对主机的设置,例如端口号、ip地址、域名、主站点、日志 (具体参考官方文档)

1.1 server下的root

root指定了主页文件的位置

server {
listen 80;
server_name  www.pc.com;
root  /data/html/;
  location /cxk {
  root  /data/cxk
  }
}

root 类似与追加
实际 你该访问的页面 是 /data/cxk/cxk/

1.2 server块 构建虚拟主机

基于域名

实验内容: 用一台服务器生成2个站点:手机端、pc端

实验步骤:

  1. 编辑主配置文件
[root@node1 ~]#  vim  /apps/nginx/conf/nginx.conf   //编辑主配置文件

http {
    include       mime.types;
    include  /apps/nginx/conf.d/*.conf;      //添加include语句
    default_type  application/octet-stream;
    server_tokens  off;

[root@node1 ~]#  nginx -s reload  //重新加载
  1. 编辑子配置文件
[root@node1 conf.d]#  cd /apps/nginx/conf.d   //切换到子配置文件目录下
[root@node1 conf.d]#  vim pc.conf     //编辑子配置文件pc.conf

server  {
listen 80;
server_name  www.pc.com;
root  /data/pc/;
}

[root@node1 conf.d]#  cp pc.conf m.conf
[root@node1 conf.d]#  vim m.conf   //编辑子配置文件m.conf
server  {
listen 80;
server_name  www.phone.com;
root  /data/phone/;
}

[root@node1 conf.d]#  nginx -t   //检查文件格式
[root@node1 conf.d]#  nginx -s reload   //重新加载
  1. 准备页面
[root@node1 data]#  mkdir  {pc,phone}    //建立pc、phone文件夹
[root@node1 data]#  cd pc
[root@node1 pc]#  echo pc > index.html   //生成pc页面
[root@node1 pc]#  cat index.html 
pc
[root@node1 pc]#  cd ..
[root@node1 data]#  cd phone/  
[root@node1 phone]#  echo phone > index.html   //生成phone页面
[root@node1 phone]#  cat index.html 
phone


[root@node2 ~]#  vim /etc/hosts     //编辑主机2配置文件,添加域名
192.168.204.10  www.pc.com  www.phone.com
  1. 验证
[root@node2 ~]#  curl www.pc.com
pc
[root@node2 ~]#  curl www.phone.com
phone

基于端口

`修改配置文件:`
[root@node1 conf.d]#  vim pc.conf   //编辑子配置文件pc.conf
server  {
listen 9527;
server_name  www.pc.com;
root  /data/pc/;
}
[root@node1 conf.d]#  vim m.conf    //编辑子配置文件m.conf
server  {
listen 80;
server_name  www.phone.com;
root  /data/phone/;
}
[root@node1 conf.d]#  nginx -t          //检查文件格式
[root@node1 conf.d]#  nginx -s reload   //重新加载

`准备页面`

`验证:`
[root@node2 ~]#  curl 192.168.204.10
phone
[root@node2 ~]#  curl 192.168.204.10:9527
pc

基于ip

`修改配置文件:`
[root@node1 conf.d]#  vim pc.conf    //编辑子配置文件pc.conf
server  {
listen 192.168.204.10:80;
server_name  www.pc.com;
root  /data/pc/;
}

[root@node1 conf.d]#  ifconfig ens33:0 192.168.204.11  //添加一个虚拟ip
[root@node1 conf.d]#  vim m.conf     //编辑子配置文件m.conf
server {
listen 192.168.204.11:80;
server_name www.phone.com;
root /data/phone;
}

[root@node1 conf.d]#  nginx -s reload   //重新加载

`准备页面`

`验证:`
[root@node2 ~]#  curl 192.168.204.10
pc
[root@node2 ~]#  curl 192.168.204.11
phone

1.3 alias 别名

alise相当于置换

server {
   listen 80;
   server_name www.pc.com;
   location /cxk {
        root /data/cxk/;
        //相当于追加,访问192.168.204.10/cxk等于访问192.168.204.10/data/cxk/cxk
        }
   location /cxk {
        alias /data/;
        //相当于替换,访问192.168.204.10/cxk就是访问192.168.204.10/data/
        }
}

2. location块(URL匹配)

在一个server中location配置段可存在多个,用于实现从url到文件系统的路径映射。

语法规则:

符号含义举例
=精确匹配location  =/cxk
^~以什么开头location  ^~ /cxk
~开启正则表达式,区分大小写location  ~ /cxk
~*开启正则表达式,不区分大小写location  ~* /cxk
不加符号匹配起始于此uri的所有的urilocation   /cxk

匹配优先级从高到低: => ^~> ~/~*>不带符号

6b15f87fda28b7bdd81c5c20b2a95a9.png

`前缀匹配:` =  ^~  不带符号  
`正则匹配:` ~  ~*           
先找出所有的前缀匹配,最后再看正则匹配

题目练习:
 location ~ /Test1/$ {
  return 200 'A位置最前的正则表达式匹配';
  }
  location ~* /Test1/(\w+)$ {
  return 200 'B长正则表达式匹配';
  }
  location ^~ /Test1/ {
  return 200 'C 停止正则表达式匹配';
  }
  location /Test1/Test2 {
  return 200 'D 无符号最长的前缀匹配';
  }
  location /Test1 {
  return 200 'E 无符号短前缀匹配';
  }
  location = /Test1 {
  return 200 'F =精确匹配!';
  }



192.168.91.100/Test1          F
192.168.91.100/Test1/         C
192.168.91.100/Test1/Test2    B
192.168.91.100/Testl/Test2/   D
192.168.91.100/testl/Test2    B

3. access 模块 (四层控制)

模块名称:ngx_http_access_module

官方帮助文档:nginx.org/en/docs/htt…

`配置示例:`
location / {
    deny  192.168.1.1;
    allow 192.168.1.0/24;
    allow 10.1.1.0/16;
    allow 2001:0db8::/32;
    deny  all;
}

4. 验证模块 需要输入用户名和密码

模块名称:ngx_http_auth_basic_module

  • 访问控制基于模块ngx_http_access_module实现,可以通过匹配客户端源IP地址进行限制
  • 注意: 如果能在防火墙设备控制,最好就不要在nginx上配置,可以更好的节约资源

语法:

Syntax:	auth_basic string | off;    //开启验证
Default:	
auth_basic off;
Context:	http, server, location, limit_except


Syntax:	auth_basic_user_file file;   //指明在什么位置
Default:	—
Context:	http, server, location, limit_except

示例:

[root@node1 conf.d]#  yum install httpd-tools -y

[root@node1 conf.d]#  htpasswd -c ./.nginxuser cxk  //-c代表新建用户名和密码对应的文件
New password: 
Re-type new password: 
Adding password for user cxk
[root@node1 conf.d]#  ls -a   //查看隐藏文件
.  ..  .nginxuser  pc.conf
[root@node1 conf.d]#  htpasswd -b ./.nginxuser wyf 123  //-b将密码跟在用户名后
Adding password for user wyf
[root@node1 conf.d]#  cat .nginxuser 
cxk:$apr1$YlYd1UCY$eGP2Dt3HeThxubtHP/KSY/
wyf:$apr1$elMuR0j7$V30h/NNbca9GmfMq9PXPN0


[root@node1 conf.d]#  vim pc.conf      //编辑配置文件
server  {
listen 80;
server_name  www.pc.com;
root  /data/;
     auth_basic    "FBI warning";      //提示信息,不是所有浏览器都有用
     auth_basic_user_file /apps/nginx/conf.d/.nginxuser;   //密码文件存放位置
}
[root@node1 conf.d]#  nginx -s reload  //重新加载

浏览器验证192.168.204.10
htpasswd2.png

5. 自定义错误页面

我们可以改变默认的错误页面,同时也可以用指定的响应状态码进行响应。

  • 可用位置:httpserverlocationif in location

语法格式:

Syntax:error_page code ... [=[response]] ur1;
Default:  -
Context:http,server,location,if in location

error_page    固定关键字
code          错误响应码(404 403等)
=             可以将响应码转换
uri           访问连接

示例: 自定义错误页面

[root@node2 ~]#  curl 192.168.204.10/xxxxxx     //显示404错误页面
<html>
<head><title>404 Not Found</title></head>
<body>
<center><h1>404 Not Found</h1></center>
<hr><center>nginx</center>
</body>
</html>

[root@node1 ~]#  vim /apps/nginx/conf.d/pc.conf  //编辑配置文件

server  {
listen 80;
server_name  www.pc.com;
root  /data/html/;
error_page 404 /40x.html;    //当出现404错误,就去/data/pc/error/这个文件夹找40x.html这个文件
 location  =/40x.html {
 root /data/pc/error;
 }
}

[root@node1 ~]#  mkdir /data/pc/error   //建立目录
[root@node1 ~]#  cd /data/pc/error
[root@node1 error]# vim  40x.html   //新建页面,此处页面名字需要和配置文件中的一致
  please call 10086 and connect admin!!!
[root@node1 html]#  nginx -s reload    //重启服务

[root@node2 ~]#  curl 192.168.204.10/xxxxxx   //显示自定义错误页面
please call 10086 and connect admin!!!

6. 自定义错误日志存放位置

语法格式:

Syntax: error_log  file  [level];
Default: error_log logs/error.log;
Context: main, http, mail, stream, server, location

error_log:固定格式  
file:文件路径
level: 级别,可以忽略不写 debug, info, notice, warn, error, crit, alert, emerg

示例: 改变错误日志的位置

[root@node1 error]#   vim /apps/nginx/conf.d/pc.conf   //修改配置文件

server  {
listen 80;
server_name  www.pc.com;
root  /data/html/;
error_log  /apps/nginx/logs/pc-error.log;  //定义错误日志文件位置
error_page 404 /40x.html;
 location  =/40x.html {
 root /data/pc/error;
 }
}

[root@node1 error]#  nginx -t      //检查格式
nginx: the configuration file /apps/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /apps/nginx/conf/nginx.conf test is successful
[root@node1 error]#  nginx -s reload         //重启服务

[root@node1 error]#  ls /apps/nginx/logs/    
access.log  error.log  nginx.pid  pc-error.log
[root@node1 error]#  tail -f /apps/nginx/logs/    //实时查看错误日志

7. 检测文件是否存在

try_files会按顺序检查文件是否存在,返回第一个找到的文件或文件夹(结尾加斜线表示为文件夹),如果所有文件或文件夹都找不到,会进行一个内部重定向到最后一个参数。只有最后一个参数可以引起一个内部重定向,之前的参数只设置内部URI的指向。最后一个参数是回退URI且必须存在,否则会出现内部500错误。

语法格式:

Syntax: try_files file ... uri;
        try_files file ... =code;
Default: —
Context: server, location

示例:

location / {
   root /data/nginx/html/pc;
   try_files $uri  $uri.html $uri/index.html /about/default.html;
  #try_files $uri $uri/index.html $uri.html =489;  //自定义错误489
}

www.pc.com/abc       
我的访问是路径下的abc文件,那按照设置,先会去找abc,没有abc会在后面加上abc.html,
再没有会在路径后补上abc/index.html,最后没有会有一个兜底的/about/default.html`例子:`
[root@node1 error]#  vim /apps/nginx/conf.d/pc.conf //修改配置文件

server  {
listen 80;
server_name  www.pc.com;
root  /data/html/;
error_log  /apps/nginx/logs/pc-error.log;
 location / {
 try_files $uri  $uri.html $uri/index.html /about/default.html;   //自定义
 }
}

[root@node1 html]#  mkdir about  //创建about目录
[root@node1 html]#  echo jiancewenjian > about/default.html   //生成页面
[root@node1 html]#  cat about/default.html
jiancewenjian
[root@node1 html]#  nginx -s reload   //重启服务

[root@node2 ~]#  curl 192.168.204.10/abc    
jiancewenjian   //显示托底文件/about/default.html内容

8. 长连接

相关设置: 可以加在全局或者server

keepalive_timeout timeout [header_timeout];  
//设定保持连接超时时长,0表示禁止长连接,默认为75s,通常配置在http字段作为站点全局配置

keepalive_requests number;  
//在一次长连接上所允许请求的资源的最大数量,默认为100次,建议适当调大,比如:500

9. 作为下载服务器配置

ngx_http_autoindex_module 模块处理以斜杠字符 "/" 结尾的请求,并生成目录列表,可以做为下载服务配置使用。

常用:

autoindex on | off;
//自动文件索引功能,默为off
autoindex_exact_size on | off;  
//计算文件确切大小(单位bytes),off 显示大概大小(单位K、M),默认on
autoindex_localtime on | off ; 
//显示本机时间而非GMT(格林威治)时间,默认off
autoindex_format html | xml | json | jsonp; 
//显示索引的页面文件风格,默认html
limit_rate rate; 
//限制响应客户端传输速率(除GET和HEAD以外的所有方法),单位B/s,即bytes/second,默认值0,表示无限制,此指令由ngx_http_core_module提供
set $limit_rate
//变量提供 限制   变量优先级高

示例:

[root@node1 html]#  vim /apps/nginx/conf.d/pc.conf  //编辑配置文件

server  {
listen 80;
server_name  www.pc.com;
root  /data/html/;
   location /download {
   autoindex on;    //开启下载服务器
   }
}
}

[root@node1 html]#  mkdir download  //创建download目录
[root@node1 html]#  cd download/
[root@node1 download]#  cp /etc/passwd /etc/fstab  /etc/issue .
[root@node1 download]#  ls
fstab  issue  passwd

[root@node1 download]#  nginx -t    //检查文件格式
nginx: the configuration file /apps/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /apps/nginx/conf/nginx.conf test is successful
[root@node1 download]#  nginx -s reload  //重启服务

浏览器验证 192.168.204.10/download

`注意:`download不需要index.html文件

作为下载服务器配置.png

10. 用户上传资料

client_max_body_size 1m; 
//设置允许客户端上传单个文件的最大值,默认值为1m,上传文件超过此值会出413错误

四、 高级配置

1. 网页的状态页

基于nginx 模块 ngx_http_stub_status_module 实现,在编译安装nginx的时候需要添加编译参数 --with-http_stub_status_module,否则配置完成之后监测会是提示语法错误。

  • 状态页用于输出nginx的基本状态信息
  • 注意: 状态页显示的是整个服务器的状态,而非虚拟主机的状态。

示例:

[root@node1 download]#  vim /apps/nginx/conf.d/pc.conf  //编辑配置文件

server  {
listen 80;
server_name  www.pc.com;
root  /data/html/;
   location /status {     //添加location
   stub_status;
   }
}

[root@node1 download]#  nginx -s reload   //重新加载
浏览器验证192.168.204.10/status

状态页.png

输出信息详解:

`示例:`
Active connections: 1 
server accepts handled requests
 28 28 27  //三个数字分别对应上面accepts,handled,requests三个值
Reading: 0 Writing: 1 Waiting: 0 

`含义:`
Active connections: 
//当前处于活动状态的客户端连接数,包括连接等待空闲连接数=reading+writing+waiting

accepts:
//统计总值,Nginx自启动后已经接受的客户端请求的总数。
handled:
//统计总值,Nginx自启动后已经处理完成的客户端请求总数,通常等于accepts,除非有因worker_connections限制等被拒绝的连接
requests:
//统计总值,Nginx自启动后客户端发来的总的请求数。

Reading//当前状态,正在读取客户端请求报文首部的连接的连接数,数值越大,说明排队现象严重,性能不足
Writing//当前状态,正在向客户端发送响应报文过程中的连接数,数值越大,说明访问量很大
Waiting//当前状态,正在等待客户端发出请求的空闲连接数,开启 keep-alive的情况下,这个值等于active – (reading+writing)

为了安全考虑,需要增加验证模块

[root@node1 download]#  vim /apps/nginx/conf.d/pc.conf  //编辑配置文件

server  {
listen 80;
server_name  www.pc.com;
root  /data/html/;
   location /status {     //添加location
   stub_status;
   auth_basic    "admin site";    //增加验证模块
   auth_basic_user_file /apps/nginx/conf.d/.httpuser;
   }
}

[root@node1 download]#  nginx -s reload   //重新加载

2. Nginx第三方模块——echo模块

[root@node1 data]#  cd /opt
[root@node1 opt]#  ls
nginx-1.18.0  nginx-1.18.0.tar.gz  rh
[root@node1 opt]#  rz     //上传echo安装包

[root@node1 opt]#  ls
echo-nginx-module-master.zip  nginx-1.18.0  nginx-1.18.0.tar.gz  rh
[root@node1 opt]#  unzip echo-nginx-module-master.zip    //解压
[root@node1 opt]#  cd nginx-1.18.0/    //切换目录
[root@node1 nginx-1.18.0]#  ls
auto     CHANGES.ru  configure  html     Makefile  objs    src
CHANGES  conf        contrib    LICENSE  man       README

[root@node1 nginx-1.18.0]#  ./configure --prefix=/apps/nginx      //重新编译
--user=nginx --group=nginx --with-http_ssl_module --with-http_v2_module 
--with-http_realip_module --with-http_stub_status_module --with-http_gzip_static_module 
--with-pcre --with-stream --with-stream_ssl_module --with-stream_realip_module 
--add-module=/opt/echo-nginx-module-master  
[root@node1 nginx-1.18.0]#  make -j2 && make install

[root@node1 nginx-1.18.0]#  systemctl restart nginx  //重启服务
[root@node1 nginx-1.18.0]#  vim /apps/nginx/conf.d/pc.conf  //编辑配置文件

server  {
listen 80;
server_name  www.pc.com;
root  /data/html/;
  location  /ip {           //添加location
  default_type   text/html;
  echo "welcome, your ip addr: ";
  echo $remote_addr;
  }
}

[root@node1 nginx-1.18.0]#  nginx -s reload   //重新加载

[root@node2 ~]#  curl 192.168.204.10/ip
welcome, your ip addr: 
192.168.204.20
//添加模块后支持echo打印变量

3. 变量

官方文档:nginx.org/en/docs/var…

3.1 内置变量

变量
$document_root;服务器的页面主站点nginx软件的根目录,在系统中的真正位置
$document_uri;客户端打在浏览器中 url
  
$remote_addr;客户端远程地址
$remote_port;客户端端口
  
$request_method;请求方式 GET
$request_filename;你访问的资源在系统上的绝对路径(真实路径)
$request_uri;包含参数的url,除了主机名和主机名前面的都包括
  
$proxy_add_x_forwarded_for把所有客户端的ip记录下来
$args;记录数据在数据库中的位置形成了一条查询数据库的语句去对接数据库
$scheme;请求的协议,http/https
$host;服务器地址 域名,如果没有域名显示ip
  
$server_addr;服务器ip地址
$server_protocol;协议版本,一般来说客户端服务端要一致
$server_name;服务器主机名
$server_port;服务器端口

示例:

[root@node1 nginx-1.18.0]#  vim /apps/nginx/conf.d/pc.conf  //编辑配置文件

server  {
listen 80;
server_name  www.pc.com;
root  /data/html/;
  location  /ip {
  root /opt;
  echo $document_root;     //服务器的页面主站点
  echo $document_uri;      //客户端打在浏览器中的url
  echo $host;              //服务器地址 域名,如果没有域名显示ip
  echo $remote_port;       //客户端端口
  echo $request_method;    //请求资源的方式
  echo $request_filename;  //你访问的资源在系统上的绝对路径(真实路径)
  echo $request_uri;       //包含参数的url,除了主机名和主机名前面的都包括
  echo $server_protocol;   //协议版本
  }
}

[root@node1 nginx-1.18.0]#  nginx -s reload   //重新加载

[root@node2 ~]#  curl 192.168.204.10/ip
/opt
/ip
192.168.204.10
39774
GET
/opt/ip
/ip
HTTP/1.1

常用变量.png

3.2 自定义变量

假如需要自定义变量名称和值,使用指令set $variable value;

语法格式:

Syntax: set $variable value;
Default: —
Context: server, location, if

示例:

[root@node1 nginx-1.18.0]#  vim /apps/nginx/conf.d/pc.conf  //编辑配置文件

server  {
listen 80;
server_name  www.pc.com;
root  /data/html/;
  location  /test {
  set $name cxk;     //自定义变量
  echo $name;
  }
}

[root@node1 nginx-1.18.0]#  nginx -s reload  //重新加载

[root@node2 ~]#  curl 192.168.204.10/test
cxk

4. 自定义访问日志

日志的格式可以自由指定

官方帮助文档:nginx.org/en/docs/htt…

语法格式:

Syntax:	access_log path [format [buffer=size] [gzip[=level]] [flush=time] [if=condition]];
access_log off;
Default:	  access_log logs/access.log combined;
Context:	http, server, location, if in location, limit_except

示例: 自定义json格式日志

[root@node1 ~]#  vim  /apps/nginx/conf/nginx.conf  //编辑主配置文件

 log_format test '{"@timestamp":"$time_iso8601",'
        '"host":"$server_addr",'
        '"clientip":"$remote_addr",'
        '"size":$body_bytes_sent,'
        '"responsetime":$request_time,'
        '"upstreamtime":"$upstream_response_time",'
        '"upstreamhost":"$upstream_addr",'  
        '"http_host":"$host",'
        '"uri":"$uri",'
        '"xff":"$http_x_forwarded_for",'
        '"referer":"$http_referer",'
        '"tcp_xff":"$proxy_protocol_addr",'
        '"http_user_agent":"$http_user_agent",'
        '"status":"$status"}';
...................
    include  /apps/nginx/conf.d/*.conf;    //注意此语句放置位置!
    
[root@node1 ~]#  vim   /apps/nginx/conf.d/pc.conf   //编辑子配置文件
server  {
listen 80;
server_name  www.pc.com;
root  /data/html/;
access_log logs/access.log test;  //启用
}

[root@node1 ~]#  nginx -t         //检查格式
[root@node1 ~]#  nginx -s reload  //重新加载

[root@node2 ~]#  curl 192.168.204.10  //主机2验证
[root@node1 ~]#  tail -f    /apps/nginx/logs/access.log   //实时查看日志

{"@timestamp":"2024-06-04T15:08:09+08:00",    '"host":"192.168.204.10",'    '"clientip":"192.168.204.20",'    
'"size":11,'    '"responsetime":0.000,'    '"upstreamtime":"-",'    '"upstreamhost":"-",'     
'"http_host":"192.168.204.10",'    '"uri":"/index.html",'    '"xff":"-",'    '"referer":"-",'    
'"tcp_xff":"-",'    '"http_user_agent":"curl/7.29.0",'    '"status":"200"}'

注意:\color{red}{注意:} 如果开启 include ,注意定义自配置文件与日志格式的上下关系,日志格式一定要在 include 之前,否则会不生效。

5. Nginx压缩功能

官方帮助文档: nginx.org/en/docs/htt…

配置指令:

gzip on | off; 
//启用或禁用gzip压缩,默认关闭

gzip_comp_level level;
//压缩比由低到高从1到9,默认为1

gzip_disable "MSIE [1-6]\."; 
//禁用IE6 gzip功能

gzip_min_length 1k; 
//gzip压缩的最小文件,小于设置值的文件将不会压缩

gzip_http_version 1.0 | 1.1; 
//启用压缩功能时,协议的最小版本,默认HTTP/1.1

gzip_buffers number size;  
//指定Nginx服务需要向服务器申请的缓存空间的个数和大小,平台不同,默认:32 4k或者16 8k;

gzip_types mime-type ...;    
//指明仅对哪些类型的资源执行压缩操作;默认为gzip_types text/html,不用显示指定,否则出错

gzip_vary on | off;
//如果启用压缩,是否在响应报文首部插入“Vary: Accept-Encoding”,一般建议打开

gzip_static on | off;
//预压缩,先压缩好,不用临时压缩,消耗cpu

示例:

[root@node1 ~]#  vim   /apps/nginx/conf.d/pc.conf  //编辑配置文件

server  {
listen 80;
server_name  www.pc.com;
root  /data/html/;
access_log logs/access.log test; 
        gzip on;             //启用gzip压缩
        gzip_comp_level 9;   //压缩比为9
        gzip_min_length 1k;  //文件小于1k不压缩
        gzip_vary on;        //启用压缩会在响应报文首部插入“Vary: Accept-Encoding”
}

[root@node1 ~]#  nginx -s reload   //重启服务

[root@node1 html]#  cd /data/html/
[root@node1 html]#  cp /etc/passwd .   //复制一个文件到当前文件夹
[root@node1 html]#  mv passwd  passwd.html   //改名,方便浏览器识别
[root@node1 html]#  vim passwd.html    //编辑文件,使其大于1k
[root@node1 html]#  ll -h              //查看文件大小
总用量 436K
drwxr-xr-x. 2 root root   26 63 18:33 about
drwxr-xr-x. 2 root root   46 63 19:11 download
-rw-r--r--. 1 root root   11 63 16:32 index.html
-rw-r--r--. 1 root root 429K 64 15:27 passwd.html   //大于1k

浏览器中访问192.168.204.10/passwd.html (注意不要在xshell中用curl验证,因为curl不支持压缩)
查看实时日志中 size 的变化
[root@node1 html]#   tail -f    /apps/nginx/logs/access.log

压缩验证.png

预压缩

[root@node1 ~]#  vim /apps/nginx/conf.d/pc.conf 

server  {
listen 80;
listen 443 ssl;
        ssl_certificate /opt/www.pc.com.crt;
        ssl_certificate_key /opt/www.pc.com.key;
server_name  www.pc.com;
root  /data/html/;
        gzip on;             //启用gzip压缩
        gzip_comp_level 9;   //压缩比为9
        gzip_min_length 1k;  //gzip压缩的最小文件,小于设置值的文件将不会压缩
        gzip_vary on;        //启用压缩会在响应报文首部插入“Vary: Accept-Encoding”
        gzip_static on;      //开启预压缩
}

[root@node1 ~]#  nginx -s reload


[root@node1 ~]#  cd /data/html/
[root@node1 html]#  cp /etc/passwd  ./passwd.html    //复制一个文件到当前目录
[root@node1 html]#  ls
about  beijing  download  index.html  passwd.html  xhr.jpg
[root@node1 html]#  gzip passwd.html                 //压缩文件
[root@node1 html]#  ls
about  beijing  download  index.html  passwd.html.gz  xhr.jpg
//注意预压缩的文件名要以.html.gz结尾


浏览器访问192.168.204.10/passwd.html
gzip压缩后/data/html中没有passwd.html这个文件,但是依旧可以访问,是因为开启了预压缩

如果要修改这个文件就解压缩
联想截图_20240606173020.png

6. https功能 ★★★

nginx 的https 功能基于模块ngx_http_ssl_module实现

官方帮助文档:nginx.org/en/docs/htt…

常用参数:

ssl on | off;   
//为指定的虚拟主机配置是否启用ssl功能,此功能在1.15.0废弃,使用listen [ssl]替代
listen 443 ssl;

ssl_certificate /path/to/file;
//指向包含当前虚拟主机和CA的两个证书信息的文件,一般是crt文件

ssl_certificate_key /path/to/file;
//当前虚拟主机使用的私钥文件,一般是key文件

ssl_protocols [SSLv2] [SSLv3] [TLSv1] [TLSv1.1] [TLSv1.2]; 
//支持ssl协议版本,早期为ssl现在是TLS,默认为后三个

ssl_session_cache off | none | [builtin[:size]] [shared:name:size];
//配置ssl缓存

ssl_session_timeout time;
//客户端连接可以复用ssl session cache中缓存的有效时长,默认5m

示例: make命令生成自签名证书

  1. 生成密钥和证书
[root@node1 ~]#  cd /etc/pki/tls/
[root@node1 tls]#  ls
cert.pem  certs  misc  openssl.cnf  private
[root@node1 tls]#  cd certs/
[root@node1 certs]#  ls
ca-bundle.crt  ca-bundle.trust.crt  make-dummy-cert  Makefile  renew-dummy-cert
[root@node1 certs]#  vim Makefile    //编辑

 55 %.key:
 56         umask 77 ; \
 57         #/usr/bin/openssl genrsa -aes128 $(KEYLEN) > $@    //注释掉
//这个命令在shell中直接运行会要求用户输入密钥加密所用的密码,并且将生成的私钥内容保存到指定的文件中。
 58         /usr/bin/openssl genrsa  $(KEYLEN) > $@    //设置为不用输入密码(注意用yy复制,前面是制表符)


[root@node1 certs]#  make www.pc.com.crt
umask 77 ; \
#/usr/bin/openssl genrsa -aes128 2048 > www.pc.com.key
/usr/bin/openssl genrsa  2048 > www.pc.com.key
Generating RSA private key, 2048 bit long modulus
................+++
.....................+++
e is 65537 (0x10001)
umask 77 ; \
/usr/bin/openssl req -utf8 -new -key www.pc.com.key -x509 -days 365 -out www.pc.com.crt 
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) []:js                               //省份
Locality Name (eg, city) [Default City]:nj                             //城市
Organization Name (eg, company) [Default Company Ltd]:bd               //公司
Organizational Unit Name (eg, section) []:it                           //部门
Common Name (eg, your name or your server's hostname) []:www.pc.com    //域名
Email Address []:                                                      //邮箱


[root@node1 certs]#  ls
ca-bundle.crt  ca-bundle.trust.crt  make-dummy-cert  Makefile  renew-dummy-cert  www.pc.com.crt  www.pc.com.key
//可以看到生成了 密钥 和 证书
  1. 编辑配置文件
[root@node1 certs]#  cp www* /opt/    //把密钥和证书文件复制到opt下
[root@node1 certs]#  cd /opt
[root@node1 opt]#  ls
echo-nginx-module-master  echo-nginx-module-master.zip  nginx-1.18.0  nginx-1.18.0.tar.gz  rh  www.pc.com.crt  www.pc.com.key

[root@node1 data]#  cd  /apps/nginx/conf.d
[root@node1 conf.d]#  vim pc.conf     //编辑配置文件

server  {
listen 80;
        listen 443 ssl;
        ssl_certificate /opt/www.pc.com.crt;
        ssl_certificate_key /opt/www.pc.com.key;
server_name  www.pc.com;
root  /data/html/;
}

[root@node1 conf.d]#  nginx -s reload    //重新加载
  1. 浏览器验证 https://192.168.204.10

证书1.png

证书2.png

7. 升级openssl

下载源码包,重新编译
--with-openssl=/data/openssl-1.1.1k

8. 自定义图标

favicon.ico 文件是浏览器收藏网址时显示的图标,当客户端使用浏览器问页面时,浏览器会自己主动发起请求获取页面的favicon.ico文件,但是当浏览器请求的favicon.ico文件不存在时,服务器会记录404日志,而且浏览器也会显示404报错。