NGINX 常见模块

NGINX 常见模块

4.11 第三方模块

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

4.11.1 nginx-module-vts 模块实现流量监控
[root@centos8 ~]#cd /usr/local/src
[root@centos8 ~]#yum -y install git
[root@centos8 src]#git clone https://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 --add-module=/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 可以看到下面显示

在这里插入图片描述

git clone —远程下载

4.11.2 echo实现信息显示

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

重新编译:都要加载;

#记得要首先关闭nginx ,在重新启动

[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/echo-
nginx-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才能访问测试,不支持reload
[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 --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
#测试查看结果
[root@centos7 ~]#curl http://www.ehuo.org/main
hello world,main-->
10.0.0.7
sub1
sub2
took 2.003 sec for total.

在这里插入图片描述

4.12 Nginx 变量使用

nginx的变量可以在配置文件中引用,作为功能判断或者日志等场景使用
变量可以分为内置变量和自定义变量
内置变量是由nginx模块自带,通过变量可以获取到众多的与客户端访问相关的值。

内置变量

$remote_addr;
#存放了客户端的地址,注意是客户端的公网IP

$args;
#变量中存放了URL中的所有参数,例如:http://www.ehuo.org/main/index.do?
id=20190221&partner=search
#返回结果为: id=20190221&partner=search

$host;
#存放了请求的host名称


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 #用下划线代替横线



4.13 Nginx自定义访问日志

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

访问日志由 ngx_http_log_module 模块实现

语法格式

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

日志格式的常见变量

$remote_addr # 记录客户端IP地址
$remote_user # 记录客户端用户名
$time_local # 记录通用的本地时间
$time_iso8601 # 记录ISO8601标准格式下的本地时间
$request # 记录请求的方法以及请求的http协议
$status # 记录请求状态码(用于定位错误信息)
$body_bytes_sent # 发送给客户端的资源字节数,不包括响应头的大小
$bytes_sent # 发送给客户端的总字节数$msec # 日志写入时间。单位为秒,精度是毫秒。
$http_referer # 记录从哪个页面链接访问过来的
$http_user_agent # 记录客户端浏览器相关信息
$http_x_forwarded_for #记录客户端IP地址
$request_length # 请求的长度(包括请求行,请求头和请求正文)。
$request_time # 请求花费的时间,单位为秒,精度毫秒
# 注:如果Nginx位于负载均衡器,nginx反向代理之后,web服务器无法直接获取到客 户端真实的IP地址。
# $remote_addr获取的是反向代理的IP地址。 反向代理服务器在转发请求的http头信息中,
# 增加X-Forwarded-For信息,用来记录客户端IP地址和客户端请求的服务器地址

默认日志格式

http {
 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 /var/log/nginx/access.log main;

日志所在地

root@rocky8 conf.d]# cd /apps/nginx/logs
[root@rocky8 logs]# ll
total 760
-rw-r--r-- 1 root root 335293 Jun  8 00:43 access.log  #原来访问的日志
-rw-r--r-- 1 root root 363680 Jun  8 00:22 error.log   #原来的错误日志
-rw-r--r-- 1 root root    829 Jun  7 12:02 m.ehuo.org-error.log  #自己定义的错误日志;
-rw-r--r-- 1 root root  13341 Jun  8 00:18 www.ehuo.org-error.log

4.13.1 自定义默认格式日志

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

#注意:此指令只支持http块,不支持server块
log_format access_log_format  '$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  access_log_format;
#重启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.ehuo.org:80
4.13.2 自定义json格式日志

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

og_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.wang.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.13.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.13.4 不记录访问日志

一个网站会包含很多元素,尤其是有大量的images、js、css等静态资源。这样的请求可以不用记录日志

#请求favicon.ico时,不记录日志
location /favicon.ico {
access_log off;
return 200;
}
#当有人访问gif、png等资源时,将日志丢入空
location ~* .*\.(gif|jpg|png|css|js)$ {
 access_log /dev/null;
}

4.14 关于 favicon.ico

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

方法一:服务器不记录访问日志:
location = /favicon.ico {
 log_not_found off;
 access_log off;
}
#方法二:将图标保存到指定目录访问:
#location ~ ^/favicon\.ico$ {
location = /favicon.ico {
  root  /data/nginx/html/pc/images;
  expires 365d;  #设置文件过期时间
  access_log off;
}
nginx/logs/access.log

log_format testlog '$remote_addr'  $remote_user [$time_local] "$request" $status $body_bytes_sent "$http_user_agent" ';



image-20220602154831980

4.15 Nginx压缩功能

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

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

#启用或禁用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/png;  #开启什么样的压缩

gzip_vary on;#head字段
#重启Nginx并访问测试:
[root@centos8 ~]# curl --head --compressed http://www.wang.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 #压缩传输

4.16 https 功能

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

在这里插入图片描述

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

ssl_session_cache off | none | [builtin[:size]] [shared:name:size];
#配置ssl缓存
 	off: #关闭缓存
	none:  #通知客户端支持ssl session cache,但实际不支持

	builtin[:size]:#使用OpenSSL内建缓存,为每worker进程私有,使用此内置缓存可能会导致内存碎片

	[shared:name:size]:#在各worker之间使用一个共享的缓存,需要定义一个缓存名称和缓存空间大小,1M可以存储4000个会话信息,多个虚拟主机可以使用相同的缓存名称

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

官方性能优化

https://nginx.org/en/docs/http/ngx_http_ssl_module.html
To reduce the processor load it is recommended to
set the number of worker processes equal to the number of processors,
enable keep-alive connections,
enable the shared session cache,
disable the built-in session cache,
and possibly increase the session lifetime (by default, 5 minutes):
worker_processes auto;
http {
 ...
 server {
   listen        443 ssl;
   keepalive_timeout  70;
   ssl_protocols    TLSv1 TLSv1.1 TLSv1.2;
   ssl_ciphers     AES128-SHA:AES256-SHA:RC4-SHA:DES-CBC3-SHA:RC4-MD5;
   ssl_certificate   /usr/local/nginx/conf/cert.pem;
   ssl_certificate_key /usr/local/nginx/conf/cert.key;
   ssl_session_cache  shared:SSL:10m;
   ssl_session_timeout 10m;
   ...
 }
4.15.2 自签名证书
[root@rocky8 conf.d]# pwd
/apps/nginx/conf.d
[root@rocky8 conf.d]# ls
m.ehuo.org.conf  mirror.ehuo.org.conf  www.ehuo.org.conf
[root@rocky8 conf.d]# mkdir ssl
[root@rocky8 conf.d]# cd ssl
[root@rocky8 ssl]#  openssl req -newkey rsa:4096 -nodes -sha256 -keyout ca.key -x509 -days 3650 -out ca.crt #自签名CA证书
Generating a RSA private key
....................................................................................................++++
.......................++++
writing new private key to 'ca.key'
-----
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) []:BEIJING #省份
Locality Name (eg, city) [Default City]:beijing #城市
Organization Name (eg, company) [Default Company Ltd]:ehuo #公司名称
Organizational Unit Name (eg, section) []:it #部门
Common Name (eg, your name or your server's hostname) []:ca.ehuo.org  #通用名称
Email Address []:  #邮箱
[root@rocky8 ssl]# ls
ca.cr  ca.key

#自制key和csr文件
[root@rocky8 ssl]#  openssl req -newkey rsa:4096 -nodes -sha256 -keyout www.ehuo.org.key -out www.ehuo.org.csr
Generating a RSA private key
.................++++
..............................................++++
writing new private key to 'www.ehuo.org.key'
-----
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) []:beijing
Locality Name (eg, city) [Default City]:beijing
Organization Name (eg, company) [Default Company Ltd]:it
Organizational Unit Name (eg, section) []:it
Common Name (eg, your name or your server's hostname) []:www.ehuo.org
Email Address []:

Please enter the following 'extra' attributes
to be sent with your certificate request
A challenge password []:
An optional company name []:
root@rocky8 ssl]# ll
total 16
-rw-r--r-- 1 root root 2021 Jun  8 23:47 ca.cr
-rw------- 1 root root 3276 Jun  8 23:46 ca.key
-rw-r--r-- 1 root root 1691 Jun  8 23:49 www.ehuo.org.csr
-rw------- 1 root root 3272 Jun  8 23:48 www.ehuo.org.key

#签发证书
root@rocky8 ssl]# openssl x509 -req -days 3650 -in www.ehuo.org.csr -CA ca.crt -CAkey ca.key -CAcreateserial -out www.ehuo.org.crt
Signature ok
subject=C = CN, ST = beijing, L = beijing, O = it, OU = ijt, CN = www.ehuo.org
Getting CA Private Key


#验证证书内容
root@rocky8 ssl]#openssl x509 -in www.ehuo.org.crt -noout -text


#合并CA和服务器证书成一个文件,注意服务器证书在前
[root@centos8 certs]#cat www.ehuo.org.crt ca.crt > www.ehuo.org.pem
4.15.3 https 配置
server {
	listen 80;
	listen 443 ssl;
	ssl_certificate /apps/nginx/ssl/www.ehuo.org.pem;
	ssl_certificate_key /apps/nginx/ssl/www.ehuo.org.key;
	ssl_session_cache shared:sslcache:20m;
	ssl_session_timeout 10m;
	root /data/nginx/html;
}
server{
    listen 443 ssl;
    server_name www.ehuo.org;
    ssl_certificate /apps/nginx/conf.d/ssl/www.ehuo.org.pem ;  
    ssl_certificate_key /apps/nginx/conf.d/ssl/www.ehuo.org.key ;
    ssl_session_cache shared:sslcache:20m;
	ssl_session_timeout 10m;
	root /data/nginx/html/pc ;                                       
    
}


#重启Nginx并访问验证

在这里插入图片描述

4.15.4 实现 HSTS

注意: 配置rewrite才能实现http跳转到https

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

4.17 Nginx防盗链

防盗链基于客户端携带的referer实现,referer是记录打开一个页面之前记录是从哪个页面跳转过来的标记信息,如果别人只链接了自己网站图片或某个单独的资源,而不是打开了网站的整个页面,这就是盗链,referer就是之前的那个网站域名

4.17.1 实现盗链

在一个web 站点盗链另一个站点的资源信息,比如:图片、视频等

#新建一个主机www.ehuo.org,盗取另一台主机www.hooyoo.org的图片
[root@centos8 conf.d]# pwd
/apps/nginx/conf/conf.d
#盗链服务器配置如下
[root@centos8 conf.d]# cat ehuo.org.conf
server {
listen 80;
server_name www.ehuo.org;
location / {
 index index.html;
 root "/data/nginx/html/ehuo";
 access_log /apps/nginx/logs/www.ehuo.org_access.log main;
}
}
#准备盗链web页面:
[root@centos8 conf.d]# mkdir /data/nginx/html/ehuo
[root@centos8 conf.d]# cat /data/nginx/html/ehuo/daolian.html
<html>
<head>
<meta http-equiv=Content-Type content="text/html;charset=utf-8">
<title>盗链</title>
</head>
<body>
<img src="http://www.hooyoo.org/images/logo.png" >
<h1 style="color:red">欢迎大家</h1>
<p><a href=http://www.hooyoo.org>ehuo</a>欢迎你</p>
</body>
</html>
#重启Nginx并访问http://www.ehuo.org/daolian.html 测试
#验证两个域名的日志,是否会在被盗链的web站点的日志中出现以下盗链日志信息:
4.17.2 实现防盗链

基于访问安全考虑,nginx支持通过ngx_http_referer_module模块,检查访问请求的referer信息是否有效实现防盗链功能

Syntax: valid_referers none | blocked | server_names | string ...;
Default: —
Context: server, location
none:#请求报文首部没有referer首部,比如用户直接在浏览器输入域名访问web网站,就没有referer信
息。
blocked:#请求报文有referer首部,但无有效值,比如为空。
server_names:#referer首部中包含本主机名及即nginx 监听的server_name。
arbitrary_string:#自定义指定字符串,但可使用*作通配符。示例: *.ehuo.org www.ehuo.*
regular expression:#被指定的正则表达式模式匹配到的字符串,要使用~开头,例如:
~.*\.ehuo\.com




定义防盗链:
root@centos8 ~]# vim /apps/nginx/conf/conf.d/pc.conf
server {
 index index.html;
 valid_referers none blocked server_names *.magedu.com *.wang.org 
~\.google\. ~\.baidu\. ~\.bing\. ~\.so\. ; #定义有效的referer
  if ($invalid_referer) { #假如是使用其他的无效的referer访问
  return 403 "Forbidden Access"; #返回状态码403
   #return 302 http:/ehuo.com/testdir/daotu.jpg;
   #rewrite ^(.*)$ /daolian.jpg break;#或者返回错误图片
 }
......
}
#重启Nginx并访问测试
#指定referer为http://www.baidu.com进行访问

[root@centos7 ~]# curl -e 'http://www.baidu.com' www.ehuo.org
#指定referer为http://www.xxx.com进行访问,被拒绝

[root@centos7 ~]# curl -e 'http://www.xxx.com' www.ehuo.org
#不加http的referer不会拒绝
[root@centos7 ~]# curl -e 'www.xxx.com' www.ehuo.org

regular expression:#被指定的正则表达式模式匹配到的字符串,要使用~开头,例如:
~.*.ehuo.com

定义防盗链:
root@centos8 ~]# vim /apps/nginx/conf/conf.d/pc.conf
server {
index index.html;
valid_referers none blocked server_names *.magedu.com *.wang.org
~.google. ~.baidu. ~.bing. ~.so. ; #定义有效的referer
if (KaTeX parse error: Expected '}', got '#' at position 20: …lid_referer) { #̲假如是使用其他的无效的refe… /daolian.jpg break;#或者返回错误图片
}

}
#重启Nginx并访问测试
#指定referer为http://www.baidu.com进行访问

[root@centos7 ~]# curl -e ‘http://www.baidu.com’ www.ehuo.org
#指定referer为http://www.xxx.com进行访问,被拒绝

[root@centos7 ~]# curl -e ‘http://www.xxx.com’ www.ehuo.org
#不加http的referer不会拒绝
[root@centos7 ~]# curl -e ‘www.xxx.com’ www.ehuo.org


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ehuo_

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值