nginx1

优化nginx ;

指定work个数,

设置cpu亲原型 cpu绑定? ,

惊群关闭设置为on, accept_mutex on; 。

服务器工作进程一次接受多个网络连接:multi_accept on;

设置优先级:worker_priority 0; #工作进程优先级,-20~20(19)

设置work进程一次打开文件个数最好与ulimit -n 或者limits.conf的值保持一致,:worker_rlimit_nofile 65536;

worker_connections 1024;#设置单个工作进程的最大并发连接数

use epoll; #使用epoll事件驱动,Nginx支持众多的事件驱动,比如:select、poll、epoll,只能设置在events模块中设置。

3、nginx核心配置详解

3.1配置文件说明

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

  • 主配置文件:nginx.conf

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

  • fastcgi, uwsgi,scgi 等协议相关的配置文件

  • mime.types:支持的mime类型,MIME(Multipurpose Internet Mail Extensions)多用途互联网邮件扩展类型,MIME消息能包含文本、图像、音频、视频以及其他应用程序专用的数据,是设定某种扩展名的文件用一种应用程序来打开的方式类型,当该扩展名文件被访问的时候,浏览器会自动使用指定应用程序来打开。多用于指定一些客户端自定义的文件名,以及一些媒体文件打开方式。MIME参考文档:https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Basics_of_HTTP/MIME_Types

格式说明

配置文件由指令与指令块构成
每条指令以;分号结尾,指令与值之间以空格符号分隔
可以将多条指令放在同一行,用分号分隔即可,但可读性差,不推荐
指令块以{ }大括号将多条指令组织在一起,且可以嵌套指令块
include语句允许组合多个配置文件以提升可维护性
使用#符号添加注释,提高可读性
使用$符号使用变量
部分指令的参数支持正则表达式

主配置文件结构:四部分

main block:主配置段,即全局配置段,对http,mail都有效

#事件驱动相关的配置
event {
...
}  
#http/https 协议相关配置段
http {
...
}          
#默认配置文件不包括下面两个块
#mail 协议相关配置段
mail {
...
}    
#stream 服务器相关配置段
stream {
...
}
#全局配置端,对全局生效,主要设置nginx的启动用户/组,启动的工作进程数量,工作模式,Nginx的PID路径,日志路径等。
user nginx nginx;
worker_processes  1;   #启动工作进程数数量
events { #events设置快,主要影响nginx服务器与用户的网络连接,比如是否允许同时接受多个网络连接,使用哪种事件驱动模型处理请求,每个工作进程可以同时支持的最大连接数,是否开启对多工作进程下的网络连接进行序列化等。
    worker_connections  1024;   #设置单个nginx工作进程可以接受的最大并发,作为web服务器的时候最大并发数为worker_connections * worker_processes,作为反向代理的时候为(worker_connections * worker_processes)/2
}
http { #http块是Nginx服务器配置中的重要部分,缓存、代理和日志格式定义等绝大多数功能和第三方模块都可以在这设置,http块可以包含多个server块,而一个server块中又可以包含多个location块,server块可以配置文件引入、MIME-Type定义、日志自定义、是否启用sendfile、连接超时时间和单个链接的请求上限等。
  include       mime.types;
  default_type application/octet-stream;
  sendfile       on; #作为web服务器的时候打开sendfile加快静态文件传输,指定是否使用sendfile系统调用来传输文件,sendfile系统调用在两个文件描述符之间直接传递数据(完全在内核中操作),从而避免了数据在内核缓冲区和用户缓冲区之间的拷贝,操作效率很高,被称之为零拷贝,硬盘 >> kernel buffer (快速拷贝到kernelsocket buffer) >>协议栈。
  keepalive_timeout  65;  #长连接超时时间,单位是秒
  server { #设置一个虚拟机主机,可以包含自己的全局快,同时也可以包含多个location模块。比如本虚拟机监听的端口、本虚拟机的名称和IP配置,多个server 可以使用一个端口,比如都使用80端口提供web服务、
      listen       80;  #配置server监听的端口
      server_name localhost; #本server的名称,当访问此名称的时候nginx会调用当前serevr内部的配置进程匹配。
      location / { #location其实是server的一个指令,为nginx服务器提供比较多而且灵活的指令,都是在location中体现的,主要是基于nginx接受到的请求字符串,对用户请求的UIL进行匹配,并对特定的指令进行处理,包括地址重定向、数据缓存和应答控制等功能都是在这部分实现,另外很多第三方模块的配置也是在location模块中配置。
          root   html; #相当于默认页面的目录名称,默认是安装目录的相对路径,可以使用绝对路径配置。
        index index.html index.htm; #默认的页面文件名称
      }
      error_page   500 502 503 504 /50x.html; #错误页面的文件名称
      location = /50x.html { #location处理对应的不同错误码的页面定义到/50x.html,这个跟对应其server中定义的目录下。
          root   html;  #定义默认页面所在的目录
      }
  }
   
#和邮件相关的配置
#mail {
#               ...
#       }         mail 协议相关配置段
#tcp代理配置,1.9版本以上支持
#stream {
#               ...
#       }       stream 服务器相关配置段
#导入其他路径的配置文件
#include /apps/nginx/conf.d/*.conf
}

 

 

[root@centous8 ~]# ls /apps/nginx#编译安装的地址
[root@centous8 ~]# vim /apps/nginx/conf/nginx.conf#在地址下找到配置文件
#user nobody;    
worker_processes  1;    #指令

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

#pid       logs/nginx.pid;


events {
  worker_connections  1024;
}             #events语句块【花括号括起来,要加分号,不严谨缩进,大小写严谨】


http {              ##http语句块,正对http协议来配置
  include       mime.types;
  default_type application/octet-stream;

server {                 #http语句块下的server语句块
      listen       80;
      server_name localhost;

       #charset koi8-r;

nginx配置文件干货

[root@centous8 ~]# grep -Ev '#|^$' /apps/nginx/conf/nginx.conf
worker_processes  1;    #指令
events {                          #语句块
  worker_connections  1024;
}
http {                       #嵌套语句块
  include       mime.types;
  default_type application/octet-stream;
  sendfile       on;
  keepalive_timeout  65;
  server {                    #一层
      listen       80;
      server_name localhost;
      location / {             # 二层
          root   html;
          index index.html index.htm;
      }
      error_page   500 502 503 504 /50x.html;
      location = /50x.html {
          root   html;
      }
  }
}
#邮件与反向代理的没有,后期需要可以往里边加

若将配置文件都放入nginx.conf文件中 ,会是文件比较大,难以维护,所以需要include,可以将向使用的文件用onclude文件包含进去。

3.2全局配置

全局配置与nginx具体功能没有关系,主要影响全局的

Main 全局配置段常见的配置指令分类

  • 正常运行必备的配置

  • 优化性能相关的配置

  • 用于调试及定位问题相关的配置

  • 事件驱动相关的配置

#user  nobody;  #启动Nginx工作进程的用户和组
worker_processes auto;  #启动Nginx工作进程的数量,一般设为和CPU核心数相同,auto自动设置一对一
worker_cpu_affinity 0001 0010 0100 1000 | auto ; #将每个Nginx工作进程绑定到指定的CPU核心,默认Nginx是不进行进程绑定的,绑定并不是意味着当前nginx进程独占以一核心CPU,但是可以保证此进程不会运行在其他核心上,这就极大减少了nginx的工作进程在不同的cpu核心上的来回跳转,减少了CPU对进程的资源分配与回收以及内存管理等,因此可以有效的提升nginx服务器的性能。
#error_log logs/error.log;
#error_log logs/error.log notice;
#error_log logs/error.log info;

#pid       logs/nginx.pid;
worker_priority 0; #工作进程优先级,-20~20(19)
worker_rlimit_nofile 65536; #所有worker进程能打开的文件数量上限,包括:Nginx的所有连接(例如与代理服务器的连接等),而不仅仅是与客户端的连接,另一个考虑因素是实际的并发连接数不能超过系统级别的最大打开文件数的限制.最好与ulimit -n 或者limits.conf的值保持一致,
daemon off;  #前台运行Nginx服务用于测试、docker等环境。
master_process off|on; #是否开启Nginx的master-worker工作模式,仅用于开发调试场景,默认为
on

events {
  worker_connections  1024;#设置单个工作进程的最大并发连接数
    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
}
}
#查看日志
[root@centous8 ~]# ls /apps/nginx
client_body_temp fastcgi_temp logs       sbin       uwsgi_temp
conf             html         proxy_temp scgi_temp
[root@centous8 ~]# ls /apps/nginx/logs
access.log error.log nginx.pid#主进程编号
[root@centous8 ~]# cat /apps/nginx/logs/error.log

范例: 实现 nginx 的高并发配置

[root@centos7 ~]#ulimit -n 102400
[root@centos7 ~]#while true;do ab -c 5000 -n 10000 http://10.0.0.8/;sleep 0.5;done #默认配置不支持高并发,会出现以下错误日志
[root@centos8 conf]#tail /apps/nginx/logs/error.log
2020/09/24 21:19:33 [crit] 41006#0: *1105860 open() "/apps/nginx/html/50x.html"
failed (24: Too many open files), client: 10.0.0.7, server: localhost, request:
"GET / HTTP/1.0", host: "10.0.0.8"
2020/09/24 21:19:33 [crit] 41006#0: accept4() failed (24: Too many open files)
2020/09/24 21:19:33 [crit] 41006#0: *1114177 open()
"/apps/nginx/html/index.html" failed (24: Too many open files), client: 10.0.0.7,
server: localhost, request: "GET / HTTP/1.0", host: "10.0.0.8"
root@centous8 ~]# vim /usr/lib/systemd/system/nginx.service
LimitNOFILE=100000   #修改可优化
[Install]
WantedBy=multi-user.target

#如果systemd启动,则需要修改nginx.service文件中加
LimitNOFILE=100000,才能有效
#如果非systemd启动,可以修改下面pam限制
[root@centos8 ~]#vim /etc/security/limits.conf
*               soft   nofile          1000000
*               hard   nofile          1000000
[root@centos8 ~]#vim /apps/nginx/conf/nginx.conf
worker_rlimit_nofile 100000;
[root@centos8 ~]#systemctl restart nginx
[root@centos8 ~]# watch -n1 'ps -axo pid,cmd,nice | grep nginx #验证进程优先级

 

3.3 http 配置块

http 协议相关的配置结构:http的设置主要与web服务相关

http {
...
...  #各server的公共配置
server {    #每个server用于定义一个虚拟主机,第一个server为默认虚拟服务器
...
}
server {    
...
server_name   #虚拟主机名
root     #主目录
alias     #路径别名
location [OPERATOR] URL {     #指定URL的特性
...
if CONDITION {
...
}
}
}
include conf.d/*.conf:a.conf b.conf......#只要是conf.d下的conf结尾的文件都识别为http语句块中的配置
}

nginx支持在一个nginx服务器上创建多个网站,每个网站有专业称呼叫:虚拟主机

虚拟主机对应的http的语句中对应叫server,一个server块就叫一个虚拟主

http 协议配置说明

http {
  include       mime.types; #导入支持的文件类型,是相dui于/apps/nginx/conf的目录
  default_type application/octet-stream; #除mime.types中文件类型外,设置其它文件默认类型,访问其它类型时会提示下载不匹配的类型文件
#日志配置部分
   #log_format main '$remote_addr - $remote_user [$time_local] "$request" '
   #                 '$status $body_bytes_sent "$http_referer" '
   #                 '"$http_user_agent" "$http_x_forwarded_for"';
   #access_log logs/access.log main;
#自定义优化参数
  sendfile       on;
   #tcp_nopush     on; #在开启了sendfile的情况下,合并请求后统一发送给客户端,必须开启
sendfile
   #tcp_nodelay   off; #在开启了keepalived模式下的连接是否启用TCP_NODELAY选项,当为off时,延迟0.2s发送,默认On时,不延迟发送,立即发送用户响应报文。
   #keepalive_timeout 0;
  keepalive_timeout  65 65; #设置会话保持时间,第二个值为响应首部:keepAlived:timeout=65,可以和第一个值不同
   #gzip on; #开启文件压缩
  server {
      listen       80; #设置监听地址和端口
      server_name localhost; #设置server name,可以以空格隔开写多个并支持正则表达式如:*.magedu.com www.magedu.* ~^www\d+\.magedu\.com$ default_server
       #charset koi8-r; #设置编码格式,默认是俄语格式,建议改为utf-8
       #access_log logs/host.access.log main;
      location / {
          root   html;
          index index.html index.htm;
      }
       #error_page 404             /404.html;
       # redirect server error pages to the static page /50x.html
       #
      error_page   500 502 503 504 /50x.html; #定义错误页面
      location = /50x.html {
          root   html;
      }
       # proxy the PHP scripts to Apache listening on 127.0.0.1:80
       #
       #location ~ \.php$ { #以http的方式转发php请求到指定web服务器
       #   proxy_pass   http://127.0.0.1;
       #}
       # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
       #
       #location ~ \.php$ { #以fastcgi的方式转发php请求到php处理
       #   root           html;
         #   fastcgi_pass   127.0.0.1:9000;
       #   fastcgi_index index.php;
       #   fastcgi_param SCRIPT_FILENAME /scripts$fastcgi_script_name;
       #   include       fastcgi_params;
       #}
       # deny access to .htaccess files, if Apache's document root
       # concurs with nginx's one
       #
       #location ~ /\.ht { #拒绝web形式访问指定文件,如很多的网站都是通过.htaccess文件来改变自己的重定向等功能。
       #   deny all;
       #}
      location ~ /passwd.html {
          deny all;
      }
  }
   # another virtual host using mix of IP-, name-, and port-based configuration
   #
   #server { #自定义虚拟server
      #   listen       8000;
   #   listen       somename:8080;
   #   server_name somename alias another.alias;
   #   location / {
   #       root   html;
   #       index index.html index.htm; #指定默认网页文件,此指令由ngx_http_index_module模块提供
   #   }
   #}
   # HTTPS server
   #
   #server { #https服务器配置
   #   listen       443 ssl;
   #   server_name localhost;
   #   ssl_certificate     cert.pem;
   #   ssl_certificate_key cert.key;
   #   ssl_session_cache   shared:SSL:1m;
   #   ssl_session_timeout 5m;
   #   ssl_ciphers HIGH:!aNULL:!MD5;
   #   ssl_prefer_server_ciphers on;
   #   location / {
   #       root   html;
   #       index index.html index.htm;
   #   }
   #}

3.3.1 MIME

#在响应报文中将指定的文件扩展名映射至MIME对应的类型
include           /etc/nginx/mime.types;
default_type     application/octet-stream;#除mime.types中的类型外,指定其它文件的默认
MIME类型,浏览器一般会提示下载
types {
  text/html html;
  image/gif gif;
  image/jpeg jpg;
}
#MIME参考文档:
https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Basics_of_HTTP/MIME_Types

 

范例: 识别php文件为text/html

[root@centos8 ~]#cat /apps/nginx/html/test.php 
<?php
phpinfo();
?>
[root@centos7 ~]#curl 10.0.0.8/test.php -I
HTTP/1.1 200 OK
Server: nginx/1.18.0
Date: Thu, 24 Sep 2020 13:54:39 GMT
Content-Type: application/octet-stream
Content-Length: 20
Last-Modified: Thu, 24 Sep 2020 13:53:26 GMT
Connection: keep-alive
ETag: "5f6ca4d6-14"
Accept-Ranges: bytes
[root@centos8 ~]#vim /apps/nginx/conf/nginx.conf
http {
  include       mime.types;
  default_type text/html;
......
[root@centos8 ~]#nginx -s reload
[root@centos7 ~]#curl 10.0.0.8/index.html -I
HTTP/1.1 200 OK
Server: nginx/1.18.0
Date: Thu, 24 Sep 2020 13:56:26 GMT
Content-Type: text/html
Content-Length: 612
Last-Modified: Thu, 24 Sep 2020 12:13:03 GMT
Connection: keep-alive
ETag: "5f6c8d4f-264"
Accept-Ranges: bytes

3.3.2 指定响应报文server首部

#是否在响应报文中的Content-Type显示指定的字符集,默认off不显示
charset charset | off;
#示例
charset utf-8;
#是否在响应报文的Server首部显示nginx版本
server_tokens on | off | build | string;

范例: 修改server字段(源吗)

[root@centous8 ~]# cd /usr/local/src/
[root@centous8 src]# ls
nginx-1.18.0 nginx-1.18.0.tar.gz
[root@centous8 src]# cd nginx-1.18.0
[root@centous8 nginx-1.18.0]# ls
auto CHANGES.ru configure html Makefile objs src
CHANGES conf contrib LICENSE man README
[root@centous8 nginx-1.18.0]# vim src/core/nginx.h
/*
* Copyright (C) Igor Sysoev
如果想自定义响应报文的nginx版本信息,需要修改源码文件,重新编译
如果server_tokens on,修改 src/core/nginx.h 修改第13-14行,如下示例
#define NGINX_VERSION     "1.68.9"
#define NGINX_VER         "wanginx/" NGINX_VERSION
如果server_tokens off,修改 src/http/ngx_http_header_filter_module.c
第49行,如下示例:
static char ngx_http_server_string[] = "Server: nginx" CRLF;
把其中的nginx改为自己想要的文字即可,如:wanginx

范例: 修改 Server 头部信息

[root@centos8 ~]#vim /usr/local/src/nginx-1.18.0/src/core/nginx.h 
#define NGINX_VERSION     "1.68.9"
#define NGINX_VER         "wanginx/" NGINX_VERSION  
[root@centos8 ~]#vim nginx-1.18.0/src/http/ngx_http_header_filter_module.c
static u_char ngx_http_server_string[] = "Server: magedu-nginx" CRLF;
[root@centos7 ~]#curl -I www.magedu.org
HTTP/1.1 200 OK
Server: wanginx/1.68.9
Date: Thu, 24 Sep 2020 07:44:05 GMT
Content-Type: text/html
Content-Length: 8
Last-Modified: Wed, 23 Sep 2020 14:39:21 GMT
Connection: keep-alive
ETag: "5f6b5e19-8"
Accept-Ranges: bytes
[root@centos8 ~]#vim /apps/nginx/conf/conf.d/pc.conf
server {
    ......
    server_tokens off;
    ......
   
[root@centos7 ~]#curl -I www.magedu.org
HTTP/1.1 200 OK
Server: magedu-nginx
Date: Thu, 24 Sep 2020 07:44:59 GMT
Content-Type: text/html
Content-Length: 8
Last-Modified: Wed, 23 Sep 2020 14:39:21 GMT
Connection: keep-alive
ETag: "5f6b5e19-8"
Accept-Ranges: bytes

3.4 核心配置示例

基于不同的IP、不同的端口以及不用得域名实现不同的虚拟主机,依赖于核心模块ngx_http_core_module实现。

3.4.1 新建一个 PC web 站点

  1. 编辑网页页面显示

  2. 配置文件编辑文件指向。

  3. 编辑访问pc网站配置

  4. 访问测试,

注意

访问不同的域名,解析成相同的IP地址,然后请求的报文中,除了tcp报文,还有http的报文,http报文头中有hosts主机头,可以判断访问的页面。

#1.定义子配置文件路径
[root@loaclhost ~]# mkdir /data/nginx/html/{pc,mobile} -pv
[root@loaclhost ~]# vim /data/nginx/html/pc/index.html
[root@loaclhost ~]# vim /data/nginx/html/mobile/index.html
[root@loaclhost ~]# cat /data/nginx/html/pc/index.html
<h1>www.bai.org<h1>
[root@loaclhost ~]# tree /data/nginx/
/data/nginx/
└── html
├── mobile
│   └── index.html
└── pc
└── index.html
3 directories, 2 files
#创建PC网站配置
2.
[root@centos8 ~]# vim /apps/nginx/conf/nginx.conf
http {
......
include /apps/nginx/conf/conf.d/*.conf#在配置文件的最后面添加此行,注意不要放在最前面,会导致前面的命令无法生效
3.
[root@loaclhost ~]# mkdir /apps/nginx/conf/conf.d/
[root@loaclhost ~]# vim /apps/nginx/conf/conf.d/pc.conf
[root@loaclhost ~]# vim /apps/nginx/conf/conf.d/mobile.conf
[root@loaclhost ~]# cat /apps/nginx/conf/conf.d/pc.conf
server{
listen 80;
server_name www.bai.org
root /data/nginx/html/pc; #存放网页目录,可以放在server,location语句块中
index index.html;#可以放在全局变量中
}
[root@loaclhost ~]# systemctl reload nginx
#访问测试
4.
[root@loaclhost ~]# curl www.bai.org
<h1>www.bai.org<h1>
[root@loaclhost ~]# curl m.bai.org
<h1>m.bai.org<h1>

 

 

3.4.2 新建一个 Mobile web 站点

image-20211211201915568

 

3.4.3 root 与 alias

root:指定web的家目录,在定义location的时候,文件的绝对路径等于 root+location

范例:

server {
listen 80;
server_name www.bai.org;
location / {
  root /data/nginx/html/pc;
}
location /about {
  root /opt/html; #必须要在html目录中创建一个名为about的目录才可以访问,否则报错。
}
}
[root@centos8 ~]# mkdir -p /opt/html/about
[root@centos8 ~]# echo about > /opt/html/about/index.html
#重启Nginx并访问测试

alias:定义路径别名,会把访问的路径重新定义到其指定的路径,文档映射的另一种机制;仅能用于location上下文,此指令使用较少

范例:

[root@loaclhost ~]# mkdir /data/nginx/html/mobile/about
[root@loaclhost ~]# vim /data/nginx/html/mobile/about/index.html
[root@loaclhost about]# cat index.html
<h1>m.bai.org/about</h1>
[root@loaclhost about]# mkdir /opt/aboutdir
[root@loaclhost about]# mv /data/nginx/html/mobile/about/index.html /opt/aboutdir/
[root@loaclhost about]# echo /opt/aboutdir/ >> /opt/aboutdir/index.html
[root@loaclhost about]# cat /opt/aboutdir/index.html
<h1>m.bai.org/about</h1>
/opt/aboutdir/

[root@loaclhost ~]# vim /apps/nginx/conf/conf.d/mobile.conf
server {
listen 80;
server_name m.bai.org;
root /data/nginx/html/mobile;
#index index.html;
location /about { #注意about后不要加/ , 使用alias的时候uri后面如果加了斜杠,则下面的路径配置必须加斜杠,否则403
alias /opt/aboutdir/ #当访问about的时候,会显示alias定义的/opt/html/about里面的内容。
root /opt;/#若是root,后直接加/opt即可。则前边about需加dir
}
}
[root@loaclhost ~]# nginx -t
[root@loaclhost ~]# systemctl reload nginx
测试
[root@loaclhost ~]# curl m.bai.org/about/
<h1>m.bai.org/about</h1>
/opt/aboutdir/

 

注意:location中使用root指令和alias指令的意义不同

root定义了子页面根的位置,具体需要root后加location后地址,alias后边更的是子网站页面的地址。

root 给定的路径对应于location中的/uri 左侧的/
alias 给定的路径对应于location中的/uri 的完整路径

3.4.4 location 的详细使用

在一个server中location配置段可存在多个,用于实现从uri到文件系统的路径映射;ngnix会根据用户请求的URI来检查定义的所有location,按一定的优先级找出一个最佳匹配,而后应用其配置在没有使用正则表达式的时候,nginx会先在server中的多个location选取匹配度最高的一个uri,uri是用户请求的字符串,即域名后面的web文件路径,然后使用该location模块中的正则url和字符串,如果匹配成功就结束搜索,并使用此location处理此请求。

可以根据优先级作为动态资源与静态资源的分开放置,一个服务器给api动态,一个给静态,可实现动静分离负载均衡

动态资源组要服务器执行后结果交给用户,如php程序

静态资源如图片,直接交给用户的资料

location 官方帮助:

http://nginx.org/en/docs/http/ngx_http_core_module.html#location

#语法规则:
location [ = | ~ | ~* | ^~ ] uri { ... }
=   #用于标准uri前,需要请求字串与uri精确匹配,大小敏感,如果匹配成功就停止向下匹配并立即处理请

^~  #用于标准uri前,表示包含正则表达式,并且匹配以指定的正则表达式开头,对uri的最左边部分做匹配
检查,不区分字符大小写
~   #用于标准uri前,表示包含正则表达式,并且区分大小写
~*  #用于标准uri前,表示包含正则表达式,并且不区分大写
不带符号 #匹配起始于此uri的所有的uri
\   #用于标准uri前,表示包含正则表达式并且转义字符。可以将 . * ?等转义为普通符号
#匹配优先级从高到低:
=, ^~, ~/~*, 不带符号

官方范例

location = / {
  [ configuration A ]
}
location / {
  [ configuration B ]
}
location /documents/ {
  [ configuration C ]
}
location ^~ /images/ {
  [ configuration D ]
}
location ~* \.(gif|jpg|jpeg)$ {
  [ configuration E ]
}
The “/” request will match configuration A(?), the “/index.html” request will
match configuration B,the “/documents/document.html” request will match configuration C, the
“/images/1.gif” request will match configuration D, and the “/documents/1.jpg”
request will match configuration E.

3.4.4.1 匹配案例-精确匹配

在server部分使用location配置一个web界面,例如:当访问nginx 服务器的/logo.jpg的时候要显示指定html文件的内容

精确匹配一般用于匹配组织的logo等相对固定的URL,匹配优先级最高

范例: 精确匹配 logo

[root@centos8 ~]# cat /apps/nginx/conf/conf.d/pc.conf 
server {
listen 80;
server_name www.magedu.org;
location / {
  root /data/nginx/html/pc;
}
location = /logo.jpg {
  root /data/nginx/images;
  index index.html;
}
}
#上传logo.jpg图片到/data/nginx/images,重启Nginx并访问测试
#访问测试:http://www.magedu.org/logo.jpg

3.4.4.2 匹配案例-区分大小写

~* 用来对用户请求的uri做模糊匹配,uri中无论都是大写、都是小写或者大小写混合,此模式也都会匹配,通常使用此模式匹配用户request中的静态资源并继续做下一步操作,此方式使用较多

注意: 此方式中,对于Linux文件系统上的文件仍然是区分大小写的,如果磁盘文件不存在,仍会提示404

#正则表达式匹配:
location ~* /A.?\.jpg {
  index index.html;
  root /opt/nginx/html/image;
}
#重启Nginx并访问测试
对于不区分大小写的location,则可以访问任意大小写结尾的图片文件,如区分大小写则只能访问Aa.jpg此类文件,不区分大小写则可以访问除了aa.jpg以外,还有其它的资源比如Aa.JPG、aA.jPG这样的混合名称文件,但是还同时也要求nginx服务器的资源目录有相应的文件,比如:必须有Aa.JPG,aA.jPG这样文件存在。

image-20211211213440759

3.4.4.4 匹配案例-URI开始

location ^~ /images {
  root /data/nginx/;
  index index.html;
}
location /api {
  alias /data/nginx/api;
  index index.html;
}  
#重启Nginx并访问测试,实现效果是访问/images和/app返回不同的结果
[root@centos8 ~]# curl http://www.magedu.org/images/
images
[root@centos8 ~]# curl http://www.magedu.org/api/
api web

3.4.4.5 匹配案例-文件名后缀

[root@centos8 ~]# mkdir /data/nginx/static
#上传一个图片到/data/nginx/static
location ~* \.(gif|jpg|jpeg|bmp|png|tiff|tif|ico|wmf|js|css)$ {
  root /data/nginx/static;
  index index.html;
}
#重启Nginx并访问测试

3.4.4.6 匹配案例-优先级

location = /1.jpg {
  root /data/nginx/static1;
  index index.html;
}
location /1.jpg {
  root /data/nginx/static2;
  index index.html;
}
location ~* \.(gif|jpg|jpeg|bmp|png|tiff|tif|ico|wmf|js)$ {
  root /data/nginx/static3;
  index index.html;
}
[root@centos8 ~]# mkdir -p /data/nginx/static{1,2,3}
#上传图片到 /data/nginx/static{1,2,3} 并重启nginx访问测试
#匹配优先级:=, ^~, ~/~*,/
location优先级:(location =) > (location ^~ 路径) > (location ~,~* 正则顺序) >
(location 完整路径) > (location 部分起始路径) > (/)

3.4.4.7 生产使用案例

#直接匹配网站根会加速Nginx访问处理
location = /index.html {
  ......;
}
location / {
  ......;
}
#静态资源配置方法1
location ^~ /static/ {
  ......;
}
#静态资源配置方法2,应用较多
location ~* \.(gif|jpg|jpeg|png|css|js|ico)$ {
  ......;
}
#多应用配置
location ~* /app1 {
    ......;
}
location ~* /app2 {
    ......;
}

3.4.5 Nginx 四层访问控制

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

官方帮助:

范例:

location = /login/ {
  root /data/nginx/html/pc;
  allow 10.0.0.0/24;
  deny all;
}
location /about {
  alias /data/nginx/html/pc;
  index index.html;
  deny  192.168.1.1;
  allow 192.168.1.0/24;
  allow 10.1.1.0/16;
  allow 2001:0db8::/32;
  deny all;  #按先小范围到大范围排序
}

3.4.6 Nginx 账户认证功能

由 ngx_http_auth_basic_module 模块提供此功能

官方帮助:

http://nginx.org/en/docs/http/ngx_http_auth_basic_module.html

范例:

#CentOS安装包
[root@centos8 ~]#yum -y install httpd-tools
#Ubuntu安装包
[root@Ubuntu ~]#apt -y install apache2-utils
#创建用户
#-b 非交互式方式提交密码
[root@centos8 ~]# htpasswd -cb /apps/nginx/conf/.htpasswd user1 123456
Adding password for user user1
[root@centos8 ~]# htpasswd -b /apps/nginx/conf/.htpasswd user2 123456
Adding password for user user2
[root@centos8 ~]# tail /apps/nginx/conf/.htpasswd
user1:$apr1$Rjm0u2Kr$VHvkAIc5OYg.3ZoaGwaGq/
user2:$apr1$nIqnxoJB$LR9W1DTJT.viDJhXa6wHv.
#安全加固
[root@centos8 ~]# chown nginx.nginx /apps/nginx/conf/.htpasswd
[root@centos8 ~]# chmod 600 /apps/nginx/conf/.htpasswd
[root@centos8 ~]# vim /apps/nginx/conf/conf.d/pc.conf
location = /login/ {
  root /data/nginx/html/pc;
  index index.html;
  auth_basic           "login password";
  auth_basic_user_file /apps/nginx/conf/.htpasswd;
}
#重启Nginx并访问测试
[root@centos6 ~]#curl http://user1:123456@www.magedu.org/login/
login page
[root@centos6 ~]#curl -u user2:123456 www.magedu.org/login/
login page

 

3.4.7 自定义错误页面

自 定义错误页,同时也可以用指定的响应状态码进行响应, 可用位置:http, server, location, if in location

error_page code ... [=[response]] uri;

范例:

listen 80;
server_name www.magedu.org;
error_page  500 502 503 504 /error.html;
location = /error.html {
  root /data/nginx/html;
}
#重启nginx并访问不存在的页面进行测试

范例: 自定义错误页面

error_page 404 /40x.html;
location = /40x.html {
root /data/html/ ;
}

范例: 如果404,就转到主页

#404转为302
#error_page 404 /index.html;
error_page  404  =302 /index.html;
error_page 500 502 503 504 /50x.html;
    location = /50x.html {
}

 

3.4.8 自定义错误日志

可以自定义错误日志

Syntax: error_log file [level];
Default:
error_log logs/error.log error;
Context: main, http, mail, stream, server, location
level: debug, info, notice, warn, error, crit, alert, emerg

范例:

[root@centos8 ~]# mkdir /data/nginx/logs
listen 80;
server_name www.magedu.org;
error_page  500 502 503 504 404 /error.html;
access_log /apps/nginx/logs/magedu-org_access.log;
error_log /apps/nginx/logs/magedu-org_error.log; #定义错误日志
location = /error.html {
  root   html;
}
#重启nginx并访问不存在的页面进行测试并验证是在指定目录生成新的日志文件

3.4.9 检测文件是否存在

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

语法格式:

syntax:try_files file...url;
try_files file ... =code;
Default: —
Context: server, location

范例: 如果不存在页面, 就转到default.html页面

location / {
  root /data/nginx/html/pc;
  index index.html;
  try_files $uri  $uri.html $uri/index.html /about/default.html;
   #try_files $uri $uri/index.html $uri.html =489;
}
[root@centos8 ~]# echo "default page" >> /data/nginx/html/pc/about/default.html
#重启nginx并测试,当访问到http://www.magedu.org/about/xx.html等不存在的uri会显示default.html,如果是自定义的状态码则会显示在返回数据的状态码中
#注释default.html行,启用上面489响应码的那一行,在其生效后再观察结果
location / {
  root /data/nginx/html/pc;
  index index.html;
   #try_files $uri $uri.html $uri/index.html /about/default.html;
      try_files $uri $uri/index.html $uri.html =489;
}
[root@centos8 ~]# curl -I http://www.magedu.org/about/xx.html
HTTP/1.1 489 #489就是自定义的状态返回码
Server: nginx
Date: Thu, 21 Feb 2019 00:11:40 GMT
Content-Length: 0
Connection: keep-alive
Keep-Alive: timeout=65

3.4.10 长连接配置

keepalive_timeout timeout [header_timeout];  #设定保持连接超时时长,0表示禁止长连接,默
认为75s,通常配置在http字段作为站点全局配置
keepalive_requests number;  #在一次长连接上所允许请求的资源的最大数量,默认为100次,建议适
当调大,比如:500

范例;

keepalive_requests 3;
keepalive_timeout  65 60;
#开启长连接后,返回客户端的会话保持时间为60s,单次长连接累计请求达到指定次数请求或65秒就会被断
开,第二个数字60为发送给客户端应答报文头部中显示的超时时间设置为60s:如不设置客户端将不显示超时
时间。
Keep-Alive:timeout=60  #浏览器收到的服务器返回的报文
#如果设置为0表示关闭会话保持功能,将如下显示:
Connection:close  #浏览器收到的服务器返回的报文
#使用命令测试:
[root@centos8 ~]# telnet www.magedu.org 80
Trying 10.0.0.8...
Connected to www.magedu.org.
Escape character is '^]'.
GET / HTTP/1.1
HOST: www.magedu.org
#Response Headers(响应头信息):
HTTP/1.1 200 OK
Server: nginx/1.18.0
Date: Thu, 24 Sep 2020 04:35:35 GMT
Content-Type: text/html
Content-Length: 7
Last-Modified: Wed, 23 Sep 2020 14:39:21 GMT
Connection: keep-alive
Keep-Alive: timeout=60
ETag: "5c8a6b3a-7"
Accept-Ranges: bytes
#页面内容
pc web

 

3.4.11 作为下载服务器配置

 

3.4.12 作为上传服务器

 

3.4.13 其他配置

 

4 Nginx 高级配置

4.1 Nginx 状态页

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

注意: 状态页显示的是整个服务器的状态,而非虚拟主机的状态

#配置示例:
location /nginx_status {
  stub_status;
  auth_basic           "auth login";
  auth_basic_user_file /apps/nginx/conf/.htpasswd;
  allow 192.168.0.0/16;
  allow 127.0.0.1;
  deny all;
}
#状态页用于输出nginx的基本状态信息:
#输出信息示例:
Active connections: 291
server accepts handled requests
16630948 16630948 31070465
上面三个数字分别对应accepts,handled,requests三个值
Reading: 6 Writing: 179 Waiting: 106
Active connections: #当前处于活动状态的客户端连接数,包括连接等待空闲连接数
=reading+writing+waiting
accepts:#统计总值,Nginx自启动后已经接受的客户端请求连接的总数。
handled:#统计总值,Nginx自启动后已经处理完成的客户端请求连接总数,通常等于accepts,除非有因
worker_connections限制等被拒绝的连接
requests:#统计总值,Nginx自启动后客户端发来的总的请求数。
Reading:#当前状态,正在读取客户端请求报文首部的连接的连接数,数值越大,说明排队现象严重,性能不足
Writing:#当前状态,正在向客户端发送响应报文过程中的连接数,数值越大,说明访问量很大
Waiting:#当前状态,正在等待客户端发出请求的空闲连接数,开启 keep-alive的情况下,这个值等于
active – (reading+writing)

范例:分析网站当前访问量

[root@centos7 ~]#curl http://wang:123456@www.wangxiaochun.com/nginx_status 2> 
/dev/null |awk '/Reading/{print $2,$4,$6}'
0 1 15

4.2 Nginx 第三方模块

第三模块是对nginx 的功能扩展,第三方模块需要在编译安装Nginx 的时候使用参数--addmodule=PATH指定路径添加,有的模块是由公司的开发人员针对业务需求定制开发的,有的模块是开源爱好者开发好之后上传到github进行开源的模块,nginx的第三方模块需要从源码重新编译进行支持

4.2.1 nginx-module-vts 模块实现流量监控

https://github.com/vozlt/nginx-module-vts

fanli:

[root@centos8 ~]#cd /usr/local/src
[root@centos8 src]#git clone git://github.com/vozlt/nginx-module-vts.git
[root@centos8 src]#cd nginx-1.18.0/
[root@centos8 nginx-1.18.0]#./configure --prefix=/apps/nginx --addmodule=/usr/local/src/nginx-module-vts
[root@centos8 nginx-1.18.0]#make && make install
[root@centos8 ~]#vim /apps/nginx/conf/nginx.conf
http {
......
vhost_traffic_status_zone;
......
server {
......
location /status {
  vhost_traffic_status_display;
vhost_traffic_status_display_format html;
}
......
}
}
[root@centos8 ~]#systemctl restart nginx
#浏览器访问:http://<nginx_ip>/status 可以看到下面显示

 

image-20211212131853572

 

image-20211212131900060

4.2.2 echo 模块实现信息显示

开源的echo模块可以用来打印信息,变量等

https://github.com/openresty/echo-nginx-module

范例:

[root@centos8 ~]# systemctl stop nginx
[root@centos8 ~]# vim /apps/nginx/conf/conf.d/pc.conf
location /main {
    index index.html;
    default_type text/html;
    echo "hello world,main-->";
    echo $remote_addr ;
    echo_reset_timer;   #将计时器开始时间重置为当前时间
    echo_location /sub1;
    echo_location /sub2;
    echo "took $echo_timer_elapsed sec for total.";
}
location /sub1 {
    echo_sleep 1;
    echo sub1;
}
location /sub2 {
    echo_sleep 1;
    echo sub2;
}
[root@centos8 ~]# /apps/nginx/sbin/nginx -t
nginx: [emerg] unknown directive "echo_reset_timer" in
/apps/nginx/conf/conf.d/pc.conf:86
nginx: configuration file /apps/nginx/conf/nginx.conf test failed
#解决以上报错问题
[root@centos8 ~]# cd /usr/local/src
[root@centos8 src]# yum install git -y
#github网站国内访问不稳定,可能无法下载
[root@centos8 src]# git clone https://github.com/openresty/echo-nginx-module.git
#如果上面链接无法下载,可以用下面链接
[root@centos8 src]# git clone https://github.com.cnpmjs.org/openresty/echonginx-module.git
[root@centos8 src]# cd nginx-1.18.0/
[root@centos8 src]# ./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 \
--with-http_perl_module \
--add-module=/usr/local/src/echo-nginx-module  #指定模块源代码路径
[root@centos8 src]# make && make install
#确认语法检测通过
[root@centos8 ~]# /apps/nginx/sbin/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
#重启nginx访问测试
[root@centos8 ~]# systemctl restart nginx
[root@centos8 ~]#nginx -V
nginx version: wanginx/1.68.9
built by gcc 8.3.1 20191121 (Red Hat 8.3.1-5) (GCC)
built with OpenSSL 1.1.1c FIPS  28 May 2019
TLS SNI support enabled
configure arguments: --prefix=/apps/nginx --user=nginx --group=nginx --withhttp_ssl_module --with-http_v2_module --with-http_realip_module --withhttp_stub_status_module --with-http_gzip_static_module --with-pcre --with-stream
--with-stream_ssl_module --with-stream_realip_module --addmodule=/usr/local/src/echo-nginx-module
#测试查看结果
[root@centos7 ~]#curl http://www.magedu.org/main
hello world,main-->
10.0.0.7
sub1
sub2
took 2.003 sec for total.

image-20211213174341650

4.3 Nginx 变量使用

nginx的变量可以在配置文件中引用,作为功能判断或者日志等场景使用

变量可以分为内置变量和自定义变量

内置变量是由nginx模块自带,通过变量可以获取到众多的与客户端访问相关的值。

4.3.1 内置变量

官方文档

http://nginx.org/en/docs/varindex.html

常用内置变量

$remote_addr; 
#存放了客户端的地址,注意是客户端的公网IP
$proxy_add_x_forwarded_for
#此变量表示将客户端IP追加请求报文中X-Forwarded-For首部字段,多个IP之间用逗号分隔,如果请求中没
有X-Forwarded-For,就使用$remote_addr
the “X-Forwarded-For” client request header field with the $remote_addr variable
appended to it, separated by a comma. If the “X-Forwarded-For” field is not
present in the client request header, the $proxy_add_x_forwarded_for variable is
equal to the $remote_addr variable.
$args;
#变量中存放了URL中的所有参数,例如:http://www.magedu.org/main/index.do?
id=20190221&partner=search
#返回结果为: id=20190221&partner=search
$is_args
#如果有参数为? 否则为空
“?” if a request line has arguments, or an empty string otherwise
$document_root;
#保存了针对当前资源的请求的系统根目录,例如:/apps/nginx/html。
$document_uri;
#保存了当前请求中不包含参数的URI,注意是不包含请求的指令,比
如:http://www.magedu.org/main/index.do?id=20190221&partner=search会被定义
为/main/index.do
#返回结果为:/main/index.do
$host;
#存放了请求的host名称
limit_rate 10240;
echo $limit_rate;
#如果nginx服务器使用limit_rate配置了显示网络速率,则会显示,如果没有设置, 则显示0
$remote_port;
#客户端请求Nginx服务器时随机打开的端口,这是每个客户端自己的端口
$remote_user;
#已经经过Auth Basic Module验证的用户名
$request_body_file;
#做反向代理时发给后端服务器的本地资源的名称
$request_method;
#请求资源的方式,GET/PUT/DELETE等
$request_filename;
#当前请求的资源文件的磁盘路径,由root或alias指令与URI请求生成的文件绝对路径,
如:/apps/nginx/html/main/index.html
$request_uri;
#包含请求参数的原始URI,不包含主机名,相当于:$document_uri?$args,例如:/main/index.do?
id=20190221&partner=search
$scheme;
#请求的协议,例如:http,https,ftp等
$server_protocol;
#保存了客户端请求资源使用的协议的版本,例如:HTTP/1.0,HTTP/1.1,HTTP/2.0等
$server_addr;
#保存了服务器的IP地址
$server_name;
#请求的服务器的主机名
$server_port;
#请求的服务器的端口号
$http_user_agent;
#客户端浏览器的详细信息
$http_cookie;
#客户端的所有cookie信息
$cookie_<name>
#name为任意请求报文首部字部cookie的key名
$http_<name>
#name为任意请求报文首部字段,表示记录请求报文的首部字段,ame的对应的首部字段名需要为小写,如果有
横线需要替换为下划线
arbitrary request header field; the last part of a variable name is the field
name converted to lower case with dashes replaced by underscores #用下划线代替横线
#示例:
echo $http_user_agent;
echo $http_host;
$sent_http_<name>
#name为响应报文的首部字段,name的对应的首部字段名需要为小写,如果有横线需要替换为下划线,此变量
有问题
echo $sent_http_server;
$arg_<name>
#此变量存放了URL中的指定参数,name为请求url中指定的参数
echo $arg_id;

范例:

[root@centos8 ~]#vi /apps/nginx/conf/conf.d/pc.conf
location /main {
    index index.html;
    default_type text/html;
    echo "hello world,main-->";
    echo $remote_addr ;
    echo $args ;
    echo $document_root;
    echo $document_uri;
    echo $host;
    echo $http_user_agent;
    echo $http_cookie;
    echo $request_filename;
    echo $scheme;
    echo $scheme://$host$document_uri?$args;
}
   
[root@centos6 ~]#curl -b title=ceo 'http://www.magedu.org/main/index.do?
id=20190221&partner=search'
hello world,main-->
10.0.0.6
id=20190221&partner=search
/apps/nginx/html
/main/index.do
www.magedu.org
curl/7.19.7 (x86_64-redhat-linux-gnu) libcurl/7.19.7 NSS/3.27.1 zlib/1.2.3
libidn/1.18 libssh2/1.4.2
title=ceo
/apps/nginx/html/main/index.do
http
http://www.magedu.org/main/index.do?id=20190221&partner=search

范例:

[root@centos8 conf.d]#vim www.conf
.....
location /echo {
       echo $request;
       echo $proxy_add_x_forwarded_for;
       echo $args;
       echo $document_uri;
       echo $request_uri;
       echo $document_root;
       echo $host;
       echo $request_method;
       echo $request_filename;
       echo $scheme;
       set  $test $http_host;
       echo $test;
       echo $http_User_Agent;
       echo $http_cookie;
       echo $cookie_key1;
  }
}
[root@centos7 ~]#curl -b 'key1=v1;key2=v2'
"http://www.magedu.org/echo/index.html?id=123456&partner=search"
GET /echo/index.html?id=123456&partner=search HTTP/1.1
10.0.0.7
id=123456&partner=search
/echo/index.html
/echo/index.html?id=123456&partner=search
/data/nginx/html/pc
www.magedu.org
GET
/data/nginx/html/pc/echo/index.html
http
www.magedu.org
curl/7.29.0
key1=v1;key2=v2
v1

4.3.2 自定义变量

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

语法格式:

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

范例:

set $name magedu;
echo $name;
set $my_port $server_port;
echo $my_port;
echo "$server_name:$server_port";
#输出信息如下
[root@centos6 ~]#curl www.magedu.org/main
magedu
80
www.magedu.org:80

4.4 Nginx 自定义访问日志

访问日志是记录客户端即用户的具体请求内容信息,而在全局配置模块中的error_log是记录nginx服务器运行时的日志保存路径和记录日志的level,因此两者是不同的,而且Nginx的错误日志一般只有一个,但是访问日志可以在不同server中定义多个,定义一个日志需要使用access_log指定日志的保存路径,使用log_format指定日志的格式,格式中定义要保存的具体日志内容。

访问日志由 ngx_http_log_module 模块实现

官方帮助文档

http://nginx.org/en/docs/http/ngx_http_log_module.html

语法格式

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

4.4.1 自定义默认格式日志

如果是要保留日志的源格式,只是添加相应的日志内容,则配置如下:

#注意:此指令只支持http块,不支持server块
log_format nginx_format1  '$remote_addr - $remote_user [$time_local] "$request"
'
                     '$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"'
'$server_name:$server_port';
#注意:此指令一定要在放在log_format命令后
access_log logs/access.log nginx_format1;
#重启nginx并访问测试日志格式
==> /apps/nginx/logs/access.log <==
10.0.0.1 - - [22/Feb/2019:08:44:14 +0800] "GET /favicon.ico HTTP/1.1" 404 162 "-
" "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:65.0) Gecko/2
0100101 Firefox/65.0" "-"www.magedu.org:80

4.4.2 自定义json格式日志

Nginx 的默认访问日志记录内容相对比较单一,默认的格式也不方便后期做日志统计分析,生产环境中通常将nginx日志转换为json日志,然后配合使用ELK做日志收集,统计和分析。

 log_format access_json '{"@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"}';
    access_log /apps/nginx/logs/access_json.log access_json;
   
#重启Nginx并访问测试日志格式,参考链接:http://json.cn/
{"@timestamp":"2019-02-
22T08:55:32+08:00","host":"10.0.0.8","clientip":"10.0.0.1","size":162,"responset
ime":0.000,"upstreamtime":"-","upstreamhost":"-
","http_host":"www.magedu.org","uri":"/favicon.ico","xff":"-","referer":"-
","tcp_xff":"","http_user_agent":"Mozilla/5.0 (Windows NT 6.1; Win64; x64;
rv:65.0) Gecko/20100101 Firefox/65.0","status":"404"}

4.4.3 json 格式的日志访问统计

#python3
[root@centos8 ~]#dnf -y install python3
[root@centos8 ~]#cat log.py
#!/usr/bin/env python3
#coding:utf-8
status_200= []
status_404= []
with open("access_json.log") as f:
   for line in f.readlines():
       line = eval(line)
       if line.get("status") == "200":
           status_200.append(line.get)
       elif line.get("status") == "404":
           status_404.append(line.get)
       else:
           print("状态码 ERROR")
       print((line.get("clientip")))
f.close()
print("状态码200的有--:",len(status_200))
print("状态码404的有--:",len(status_404))
#python2
[root@centos8 ~]#dnf -y install python2
[root@centos8 ~]#cat log.py
#!/usr/bin/env python
#coding:utf-8
status_200= []
status_404= []
with open("access_json.log") as f:
   for line in f.readlines():
       line = eval(line)
       if line.get("status") == "200":
           status_200.append(line.get)
       elif line.get("status") == "404":
           status_404.append(line.get)
       else:
           print("状态码 ERROR")
       print(line.get("clientip"))
f.close()
print "状态码200的有--:",len(status_200)
print "状态码404的有--:",len(status_404)
#保存日志文件到指定路径并进测试:
[root@centos7 ~]# python nginx_json.py
状态码200的有--: 1910
状态码404的有--: 13
   
   
#转换python2语法到python3
[root@centos8 ~]#pip3 install 2to3
[root@centos8 ~]#2to3 -w log.py

4.5 Nginx 压缩功能

Nginx支持对指定类型的文件进行压缩然后再传输给客户端,而且压缩还可以设置压缩比例,压缩后的文件大小将比源文件显著变小,这样有助于降低出口带宽的利用率,降低企业的IT支出,不过会占用相应的CPU资源。

Nginx对文件的压缩功能是依赖于模块 ngx_http_gzip_module,默认是内置模块

官方文档: https://nginx.org/en/docs/http/ngx_http_gzip_module.html

配置指令如下:

#启用或禁用gzip压缩,默认关闭
gzip on | off;
#压缩比由低到高从1到9,默认为1
gzip_comp_level level;
#禁用IE6 gzip功能
gzip_disable "MSIE [1-6]\.";
#gzip压缩的最小文件,小于设置值的文件将不会压缩
gzip_min_length 1k;
#启用压缩功能时,协议的最小版本,默认HTTP/1.1
gzip_http_version 1.0 | 1.1;
#指定Nginx服务需要向服务器申请的缓存空间的个数和大小,平台不同,默认:32 4k或者16 8k;
gzip_buffers number size;  
#指明仅对哪些类型的资源执行压缩操作;默认为gzip_types text/html,不用显示指定,否则出错
gzip_types mime-type ...;
#如果启用压缩,是否在响应报文首部插入“Vary: Accept-Encoding”,一般建议打开
gzip_vary on | off;
#预压缩,即直接从磁盘找到对应文件的gz后缀的式的压缩文件返回给用户,无需消耗服务器CPU
#注意: 来自于ngx_http_gzip_static_module模块
gzip_static on | off;
#重启nginx并进行访问测试压缩功能
[root@centos8 ~]# cp /apps/nginx/logs/access.log /data/nginx/html/pc/m.txt
[root@centos8 ~]# echo "test" > /data/nginx/html/pc/test.html #小于1k的文件测试是否
会压缩
[root@centos8 ~]# vim /apps/nginx/conf/nginx.conf
gzip on;
gzip_comp_level 5;
gzip_min_length 1k;
gzip_types text/plain application/javascript application/x-javascript text/css
application/xml text/javascript application/x-httpd-php image/gif image/png;  
gzip_vary on;
#重启Nginx并访问测试:
[root@centos8 ~]# curl --head --compressed http://www.magedu.org/test.html
HTTP/1.1 200 OK
Server: nginx
Date: Fri, 22 Feb 2019 01:52:23 GMT
Content-Type: text/html
Last-Modified: Thu, 21 Feb 2019 10:31:18 GMT
Connection: keep-alive
Keep-Alive: timeout=65
Vary: Accept-Encoding
ETag: W/"5c6e7df6-171109"
Content-Encoding: gzip #压缩传输
#验证不压缩访问的文件大小:

image-20211215194259679

image-20211215194304693

image-20211215194309058

验证压缩后访问的文件大小:

image-20211215194320243

image-20211215194338407

4.6 https 功能

Web网站的登录页面通常都会使用https加密传输的,加密数据以保障数据的安全,HTTPS能够加密信息,以免敏感信息被第三方获取,所以很多银行网站或电子邮箱等等安全级别较高的服务都会采用HTTPS协议,HTTPS其实是有两部分组成:HTTP + SSL / TLS,也就是在HTTP上又加了一层处理加密信息的模块。服务端和客户端的信息传输都会通过TLS进行加密,所以传输的数据都是加密后的数据。

image-20211215194412549

https 实现过程如下:
1.客户端发起HTTPS请求:
客户端访问某个web端的https地址,一般都是443端口
2.服务端的配置:
采用https协议的服务器必须要有一套证书,可以通过一些组织申请,也可以自己制作,目前国内很多网站都
自己做的,当你访问一个网站的时候提示证书不可信任就表示证书是自己做的,证书就是一个公钥和私钥匙,
就像一把锁和钥匙,正常情况下只有你的钥匙可以打开你的锁,你可以把这个送给别人让他锁住一个箱子,里
面放满了钱或秘密,别人不知道里面放了什么而且别人也打不开,只有你的钥匙是可以打开的。
3.传送证书:
服务端给客户端传递证书,其实就是公钥,里面包含了很多信息,例如证书得到颁发机构、过期时间等等。
4.客户端解析证书:
这部分工作是有客户端完成的,首先回验证公钥的有效性,比如颁发机构、过期时间等等,如果发现异常则会
弹出一个警告框提示证书可能存在问题,如果证书没有问题就生成一个随机值,然后用证书对该随机值进行加
密,就像2步骤所说把随机值锁起来,不让别人看到。
5.传送4步骤的加密数据:
就是将用证书加密后的随机值传递给服务器,目的就是为了让服务器得到这个随机值,以后客户端和服务端的
通信就可以通过这个随机值进行加密解密了。
6.服务端解密信息:
服务端用私钥解密5步骤加密后的随机值之后,得到了客户端传过来的随机值(私钥),然后把内容通过该值进
行对称加密,对称加密就是将信息和私钥通过算法混合在一起,这样除非你知道私钥,不然是无法获取其内部
的内容,而正好客户端和服务端都知道这个私钥,所以只要机密算法够复杂就可以保证数据的安全性。
7.传输加密后的信息:
服务端将用私钥加密后的数据传递给客户端,在客户端可以被还原出原数据内容。
8.客户端解密信息:
客户端用之前生成的私钥获解密服务端传递过来的数据,由于数据一直是加密的,因此即使第三方获取到数据
也无法知道其详细内容。

4.6.1 https 配置参数

nginx 的https 功能基于模块ngx_http_ssl_module实现,因此如果是编译安装的nginx要使用参数ngx_http_ssl_module开启ssl功能,但是作为nginx的核心功能,yum安装的nginx默认就是开启的,编译安装的nginx需要指定编译参数--with-http_ssl_module开启

官方文档:

 

配置参数如下:

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缓存
  off: #关闭缓存
none:  #通知客户端支持ssl session cache,但实际不支持
builtin[:size]:#使用OpenSSL内建缓存,为每worker进程私有
[shared:name:size]:#在各worker之间使用一个共享的缓存,需要定义一个缓存名称和缓存空间大
小,一兆可以存储4000个会话信息,多个虚拟主机可以使用相同的缓存名称
ssl_session_timeout time;
#客户端连接可以复用ssl session cache中缓存的有效时长,默认5m

4.6.2 自签名证书

#自签名CA证书
[root@centos8 ~]# cd /apps/nginx/
[root@centos8 nginx]# mkdir certs
[root@centos8 nginx]# cd certs/
[root@centos8 nginx]# openssl req -newkey rsa:4096 -nodes -sha256 -keyout
ca.key -x509 -days 3650 -out ca.crt #自签名CA证书
Generating a 4096 bit RSA private key
.................++
.....
Country Name (2 letter code) [XX]:CN #国家代码
State or Province Name (full name) []:BeiJing   #省份
Locality Name (eg, city) [Default City]:Beijing #城市名称
Organization Name (eg, company) [Default Company Ltd]:magedu.Ltd #公司名称  
Organizational Unit Name (eg, section) []:magedu #部门
Common Name (eg, your name or your server's hostname) []:ca.magedu.org #通用名称
Email Address []: #邮箱
[root@centos8 certs]# ll ca.crt
-rw-r--r-- 1 root root 2118 Feb 22 12:10 ca.crt
#自制key和csr文件
[root@centos8 certs]# openssl req -newkey rsa:4096 -nodes -sha256 -keyout
www.magedu.org.key     -out www.magedu.org.csr
Generating a 4096 bit RSA private key
........................................................................++
......
Country Name (2 letter code) [XX]:CN
State or Province Name (full name) []:BeiJing
Locality Name (eg, city) [Default City]:BeiJing
Organization Name (eg, company) [Default Company Ltd]:magedu.org
Organizational Unit Name (eg, section) []:magedu.org
Common Name (eg, your name or your server's hostname) []:www.magedu.org
Email Address []:2973707860@qq.com
Please enter the following 'extra' attributes
to be sent with your certificate request
A challenge password []:      
An optional company name []:
[root@centos8 certs]# ll
total 16
-rw-r--r-- 1 root root 2118 Feb 22 12:10 ca.crt
-rw-r--r-- 1 root root 3272 Feb 22 12:10 ca.key
-rw-r--r-- 1 root root 1760 Feb 22 12:18 www.magedu.org.csr
-rw-r--r-- 1 root root 3272 Feb 22 12:18 www.magedu.org.key
#签发证书
[root@centos8 certs]# openssl x509 -req -days 3650 -in www.magedu.org.csr -CA
ca.crt -CAkey ca.key -CAcreateserial -out www.magedu.org.crt
#验证证书内容
[root@centos8 certs]# openssl x509 -in www.magedu.org.crt -noout -text
Certificate:
  Data:
      Version: 1 (0x0)
      Serial Number:
          bb:76:ea:fe:f4:04:ac:06
  Signature Algorithm: sha256WithRSAEncryption
      Issuer: C=CN, ST=BeiJing, L=Beijing, O=magedu.Ltd, OU=magedu,
CN=magedu.ca/emailAddress=2973707860@qq.com
      Validity
          Not Before: Feb 22 06:14:03 2019 GMT
          Not After : Feb 22 06:14:03 2020 GMT
      Subject: C=CN, ST=BeiJing, L=BeiJing, O=magedu.org, OU=magedu.org,
CN=www.magedu.org/emailAddress=2973707860@qq.com
      Subject Public Key Info:
          Public Key Algorithm: rsaEncryption
              Public-Key: (4096 bit)
               
#合并CA和服务器证书成一个文件,注意服务器证书在前
[root@centos8 certs]#cat www.magedu.org.crt ca.crt > www.magedu.org.pem

4.6.3 https 配置

server {
listen 80;
listen 443 ssl;
ssl_certificate /apps/nginx/certs/www.magedu.org.pem;
ssl_certificate_key /apps/nginx/certs/www.magedu.org.key;
ssl_session_cache shared:sslcache:20m;
ssl_session_timeout 10m;
root /data/nginx/html;
}
#重启Nginx并访问验证

image-20211215194658607

image-20211215194711849

 

image-20211215194727293

4.6.4 实现多域名 https

 

 

4.6.5 实现 HSTS

范例:

server {
  listen 443 ssl;
  server_name www.magedu.org;
  add_header Strict-Transport-Security "max-age=31536000; includeSubDomains"
always;
  location / {
      if ( $scheme = http ) {
        rewrite ^/(.*)$ https://www.magedu.org/$1 redirect;                  
                           
      }
  .....
  }
}

 

 

 

 

 

 

 

#./configure --prefix=/apps/nginx --user=nginx --group=nginx --with-http_ssl_module --with-http_v2_module --withhttp_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=/usr/local/src/echo-nginx-module -withopenssl=/usr/local/src/openssl-1.1.1h

 

 

 

 

 

[root@loaclhost ~]# cd /usr/local/src
[root@loaclhost src]# ls
nginx-1.18.0 nginx-1.18.0.tar.gz openssl-1.1.1h openssl-3.0.1.tar.gz
[root@loaclhost src]# tar xf openssl-3.0.1.tar.gz
[root@loaclhost src]# ls
echo-nginx-module-master.zip nginx-1.18.0.tar.gz openssl-3.0.1
nginx-1.18.0 openssl-1.1.1h openssl-3.0.1.tar.gz
[root@loaclhost src]# unzip echo-nginx-module-master.zip
[root@loaclhost src]# cd nginx-1.18.0
[root@loaclhost src]# cd 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=/usr/local/src/echo-nginx-module-master --with-openssl=/usr/local/src/openssl-1.1.1m
[root@loaclhost src]# cd nginx-1.18.0make -j 2 && make install
[root@loaclhost src]# cd nginx-1.18.0 systemctl restart nginx
升级openssl并安装echo模块

 

 

 

 

 

 

 

 

5、rewirte:地址重写

Nginx服务器利用 ngx_http_rewrite_module 模块解析和处理rewrite请求,

 

 

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

server{
listen 80;
server_name www.bai.org;
root /data/nginx/html/pc;
index index.html;
location /main {
set $name magedu;
echo $name;
set $my_port $server_port;
echo $my_port;
echo "$server_name:$server_port";
}
}
[root@loaclhost ~]# curl www.bai.org/main/
magedu
80
www.bai.org:80

 

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

server{
listen 80;
server_name www.bai.org;
root /data/nginx/html/pc;
default_type text/html;
location /main {
if ( $scheme = http ){
return 666;
echo "if----> $scheme";
}
}
}
[root@text ~]# curl -I http://www.bai.org/main
HTTP/1.1 666
Server: nginx/1.18.0
Date: Fri, 17 Dec 2021 08:38:36 GMT
Content-Length: 0
Connection: keep-alive


 

 

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

server{
listen 80;
server_name www.bai.org;
root /data/nginx/html/pc;
default_type text/html;
location /main {
if ( $scheme = http ){
return 301 http://www.baidu.com;
echo "if----> $scheme";
}
}
}
[root@text ~]# curl -I http://www.bai.org/main
HTTP/1.1 301 Moved Permanently
Server: nginx/1.18.0
Date: Fri, 17 Dec 2021 08:53:51 GMT
Content-Type: text/html
Content-Length: 169
Connection: keep-alive
Location: http://www.baidu.com

 

[root@centos7f ~]# cd /etc/pki/tls/certs
[root@centos7f certs]# ls
ca-bundle.crt ca-bundle.trust.crt make-dummy-cert Makefile renew-dummy-cert
[root@centos7f certs]# make www.bai.org.crt #证书脚本
[root@centos7f certs]# ls
ca-bundle.crt make-dummy-cert renew-dummy-cert www.bai.org.key
ca-bundle.trust.crt Makefile www.bai.org.crt
[root@centos7f certs]# scp www.bai.org.* 10.0.0.9:/apps/nginx/conf/conf.d/
The authenticity of host '10.0.0.9 (10.0.0.9)' can't be established.
[root@loaclhost conf.d]# ls
mobile.conf pc.conf www.bai.org.crt www.bai.org.key


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

server{
listen 80;
server_name www.bai.org;
root /data/nginx/html/pc;
default_type text/html;
}
server {
listen 443 ssl;
server_name www.bai.org;
ssl_certificate /apps/nginx/conf/conf.d//www.bai.org.crt;
ssl_certificate_key /apps/nginx/conf/conf.d//www.bai.org.key;
location / {
root /data/nginx/html/pc;
}
}
[root@loaclhost ~]# vim /apps/nginx/conf/conf.d/pc.conf #将上面两个server合并为一个

server{
listen 80;
listen 443 ssl;
server_name www.bai.org;
if ( $scheme = http ){
return 302 https://$server_name$request_uri;
}
ssl_certificate /apps/nginx/conf/conf.d//www.bai.org.crt;
ssl_certificate_key /apps/nginx/conf/conf.d//www.bai.org.key;
location / {
root /data/nginx/html/pc;
}
}

[root@text ~]# curl http://www.bai.org
<h1>www.bai.org<h1>
[root@text ~]# curl -k https://www.bai.org
<h1>www.bai.org<h1>


[root@loaclhost ~]# cd /data/nginx/html/pc/
[root@loaclhost pc]# ls
index.html
[root@loaclhost pc]# vim test
[root@loaclhost pc]# vim test/index.html
[root@loaclhost test]# cat index.html
test/index.html

 

 

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

server{
listen 80;
server_name www.bai.org;
root /data/nginx/html/pc;
default_type text/html;
rewrite / http://www.bibi.com permanent;
}
301,永久重定向
302 临时重定向
return 302 https://$server_name$request_uri;

5.3 nginx 的防盗链

 

在被盗服务器的server与location都可以写防盗链

valid_referers none blocked server_names
*.example.com example.* www.example.org/galleries/
~\.google\.;

if ($invalid_referer) {
return 403;
}

image-20211218123739464

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

posted @   爬上山丘  阅读(125)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 一文读懂知识蒸馏
· 终于写完轮子一部分:tcp代理 了,记录一下
点击右上角即可分享
微信分享提示