菜单 学习猿地 - LMONKEY

VIP

开通学习猿地VIP

尊享10项VIP特权 持续新增

知识通关挑战

打卡带练!告别无效练习

接私单赚外块

VIP优先接,累计金额超百万

学习猿地私房课免费学

大厂实战课仅对VIP开放

你的一对一导师

每月可免费咨询大牛30次

领取更多软件工程师实用特权

入驻
9
0

Nginx 高级配置

原创
05/13 14:22
阅读数 81801

Nginx 高级配置

Nginx 状态页

基于nginx模块ngx_http_auth_basic_module实现,在编译安装nginx的时候需要添加编译参数--withhttp_stub_status_module,否则配置完成之后监测会是提示语法错误。
  1. 配置示例:
[root@ubuntu ~]#vim /apps/nginx/conf/conf.d/pc.conf 
        location /nginx_status {    # 这项值是什么访问后面的uri就加什么。
                stub_status;
                allow 192.168.0.0/16; # 只允许这个网段查看
                allow 127.0.0.1;      # 只允许本机查看
                deny all;             # 拒绝所有
        }                             # 最后的意思就是允许192.168.0.0/16、127.0.0.1(本机)其他的都拒绝。
# 重新加载服务
[root@ubuntu ~]#systemctl reload nginx.service 
  1. 状态页作用
状态页用于输出nginx的基本状态信息:
    输出信息示例:
    Active connections: 291
    server accepts handled requests
        16630948 16630948 31070465
        上面三个数字分别对应accepts,handled,requests三个值
    Reading: 6 Writing: 179 Waiting: 106
  1. 状态页各项值的意思
Active connections: 当前处于活动状态的客户端连接数,包括连接等待空闲连接数。
accepts:统计总值,Nginx自启动后已经接受的客户端请求的总数。
handled:统计总值,Nginx自启动后已经处理完成的客户端请求的总数,通常等于accepts,除非有因
worker_connections限制等被拒绝的连接。
requests:统计总值,Nginx自启动后客户端发来的总的请求数。
Reading:当前状态,正在读取客户端请求报文首部的连接的连接数。
Writing:当前状态,正在向客户端发送响应报文过程中的连接数。
Waiting:当前状态,正在等待客户端发出请求的空闲连接数,开启 keep-alive的情况下,这个值等于 active –
(reading+writing),
  1. 测试示例
    在这里插入图片描述

Nginx 第三方模块

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

比如开源的echo模块这里呢就演示一个echo模块的编译,配置。

  1. echo模块下载
[root@ubuntu ~]#cd /usr/local/src/  # 最好和源码目录放在一起方便管理。
[root@ubuntu src]#git clone https://github.com/openresty/echo-nginx-module
Cloning into 'echo-nginx-module'...
remote: Enumerating objects: 18, done.
remote: Counting objects: 100% (18/18), done.
remote: Compressing objects: 100% (13/13), done.
remote: Total 3015 (delta 8), reused 11 (delta 5), pack-reused 2997
Receiving objects: 100% (3015/3015), 1.15 MiB | 100.00 KiB/s, done.
Resolving deltas: 100% (1619/1619), done.

[root@ubuntu src]#ll
total 16
drwxr-xr-x  4 root root 4096 Jan 10 20:36 ./
drwxr-xr-x 10 root root 4096 Jan 10 20:36 ../
drwxr-xr-x  6 root root 4096 Jan 10 20:23 echo-nginx-module/
drwxr-xr-x  9 1001 1001 4096 Jan  5 17:11 nginx-1.16.1/
  1. echo模块打入(编译)nginx
[root@ubuntu src]#/apps/nginx/sbin/nginx -V  # 使用-V找到上次编译参数(注意是上次的编译参数不是最初编译参数)
nginx version: nginx/1.16.1
built by gcc 7.4.0 (Ubuntu 7.4.0-1ubuntu1~18.04.1) 
built with OpenSSL 1.1.1  11 Sep 2018
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
[root@ubuntu src]#cd nginx-1.16.1/   # 进入源码目录下
[root@ubuntu nginx-1.16.1]#systemctl stop nginx.service # 编译前关闭服务
# 查看新添加模块语法
[root@ubuntu nginx-1.16.1]#./configure --help|grep add
  --with-http_addition_module        enable ngx_http_addition_module
  --add-module=PATH                  enable external module  # 使用这个添加新模块
  --add-dynamic-module=PATH          enable dynamic external module
  --with-cc-opt=OPTIONS              set additional C compiler options
  --with-ld-opt=OPTIONS              set additional linker options
  --with-pcre-opt=OPTIONS            set additional build options for PCRE
  --with-zlib-opt=OPTIONS            set additional build options for zlib
  --with-openssl-opt=OPTIONS         set additional build options for OpenSSL
# 复制上一次的编译参数后面添加新的模块
# 开始编译
[root@ubuntu nginx-1.16.1]#./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 (这一步就是添加echo模块)--add-module=/usr/local/src/echo-nginx-module
[root@ubuntu nginx-1.16.1]#make
[root@ubuntu nginx-1.16.1]#make install
  1. echo模块使用
  • 示例1:
[root@ubuntu nginx-1.16.1]#vim /apps/nginx/conf/conf.d/pc.conf 
location / {
                root /data/nginx/html/pc;  # 定义访问根目录
                default_type text/html;    # 定义访问以文本方式访问(因为主配置默认这个选项为下载)
                echo hello world;          # echo一个字段访问显示
        }
[root@ubuntu nginx-1.16.1]#/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
# 启动服务
[root@ubuntu nginx-1.16.1]#systemctl start nginx.service
  • 示例2:
[root@ubuntu nginx-1.16.1]#vim /apps/nginx/conf/conf.d/pc.conf 
        location /main {
                index index.html;
                default_type text/html;                            # 以什么方式查看
                echo "hello world,main-->";                        # 显示的字段 
                echo_reset_timer;
                echo_location /sub1;                               # 这个是调用后面的location /sub1
                echo_location /sub2;                               # 这个是调用后面的location /sub2
                echo "took $echo_timer_elapsed sec for total.";    # 这个是个$echo_timer_elapsed时间计算器(计算总的处理花了多少时间)
        }
        location /sub1 {      # 这个location前面的location /main调用
                echo_sleep 1; # 休眠1秒
                echo sub1;    # 显示的字段
        }
        location /sub2 {      # 这个location前面的location /main调用
                echo_sleep 1; # 休眠1秒
                echo sub2;    # 显示的字段
        }
[root@ubuntu nginx-1.16.1]#systemctl reload nginx.service 
  1. 测试访问
  • 示例1测试
    在这里插入图片描述
  • 示例2测试
    在这里插入图片描述
    开源模块平台有兴趣可以研究这个上面有很多的开源模块

Nginx 变量使用

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

内置变量

    变量常用使用方法:
                    日志记录
                    取值判断
$remote_addr;
#存放了客户端的地址,注意是客户端的公网IP,也就是一家人访问一个网站,则会显示为路由器的公网IP。

$args;
#变量中存放了URL中的指令,例如http://www.magedu.net/main/index.do?
id=20190221&partner=search中的id=20190221&partner=search

$document_root;
#保存了针对当前资源的请求的系统根目录,如/apps/nginx/html。

$document_uri;
#保存了当前请求中不包含指令的URI,注意是不包含请求的指令,比如
http://www.magedu.net/main/index.do?id=20190221&partner=search会被定义为/main/index.do 。

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

$http_user_agent;
#客户端浏览器的详细信息

$http_cookie;
#客户端的cookie信息。

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,不包含主机名,如:/main/index.do?id=20190221&partner=search 。

$scheme;
#请求的协议,如ftp,https,http等。

$server_protocol;
#保存了客户端请求资源使用的协议的版本,如HTTP/1.0,HTTP/1.1,HTTP/2.0等。

$server_addr;
#保存了服务器的IP地址。

$server_name;
#请求的服务器的主机名。

$server_port;
#请求的服务器的端口号。
  • 内置变量使用方法(这里就示例一个变量。)
[root@ubuntu ~]#vim /apps/nginx/conf/conf.d/pc.conf 
        location / {
                root /data/nginx/html/pc;
                index index.html;
                default_type text/html; # 加上这个以文本方式查看,要不会下载。
                echo $remote_port;      # 使用内置变量直接echo就可以。
        }
# 检查语法
[root@ubuntu ~]#/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
# 重新加载配置
[root@ubuntu ~]#systemctl reload nginx.service
  • 测试访问
    在这里插入图片描述

自定义变量

假如需要自定义变量名称和值,使用指令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@ubuntu ~]#vim /apps/nginx/conf/conf.d/pc.conf 
 location / {
                root /data/nginx/html/pc;
                index index.html;
                default_type text/html;
                set $NAME opengsd;
                echo $NAME;
        }
[root@ubuntu ~]#/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
[root@ubuntu ~]#systemctl reload nginx.service 
  • 调用内置变量重定值
[root@ubuntu ~]#vim /apps/nginx/conf/conf.d/pc.conf 
location / {
                root /data/nginx/html/pc;
                index index.html;
                default_type text/html;
                set $IP $remote_addr;
                echo $IP;
        }
[root@ubuntu ~]#/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
[root@ubuntu ~]#systemctl reload nginx.service 
  • 自定义变量测试访问
    在这里插入图片描述
  • 调用内置变量重定值测试访问
    在这里插入图片描述

Nginx 自定义访问日志

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

官方文档

自定义默认格式日志

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

[root@ubuntu ~]#vim /apps/nginx/conf/nginx.conf
        http {           # 必须写在http字段里
        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';
        access_log logs/access.log nginx_format1;
        }

#重启nginx并访问测试日志格式
==> /apps/nginx/logs/access.log <==
192.168.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.net:80

自定义json格式日志

    Nginx 的默认访问日志记录内容相对比较单一,默认的格式也不方便后期做日志统计分析,生产环境中通常将nginx日志转换为json日志,然后配合使用ELK做日志收集-统计-分析。
[root@ubuntu ~]#vim /apps/nginx/conf/nginx.conf
http {
    #access_log  logs/access.log  main;
    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",'
                '"domain":"$host",'
                '"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并访问测试日志格式
[root@ubuntu ~]#/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
[root@ubuntu ~]#systemctl reload nginx.service 
[root@ubuntu ~]#tail  -f /apps/nginx/logs/access_json.log  # 监控日志
{"@timestamp":"2020-01-11T15:05:40+08:00","host":"192.168.39.184","clientip":"192.168.39.1","size":23,"responsetime":0.000,"upstreamtime":"-","upstreamhost":"-","http_host":"www.opengsd.net","uri":"/","domain":"www.opengsd.net","xff":"-","referer":"-","tcp_xff":"","http_user_agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.117 Safari/537.36","status":"200"}
  • 可以在网上找解析json格式的软件 显示正确的json是正确的。
    在这里插入图片描述
  • 缺少东西校验
    在这里插入图片描述
    注意事项:
        主配置文件配置了json这个子配置其实就没有必要在配置一个日志收集。(如果想单独收集每个域名的日志还是可以配置在子配置里)子配置文件收集日志的配置最好配置location字段,不要配置在server全局字段。

json格式的日志访问统计

  • python脚本日志访问统计
# 下载python2因为写的时候用的python2
[root@ubuntu ~]#apt install python2.7  

# 准备日志最好各种状态码都有的日志(要nginx的访问日志)
[root@ubuntu logs]#ll access_json.log 
-rw-r--r-- 1 root root 80041 Jan 11 16:01 access_json.log

# 创建脚本(必须在你日志存放的那个目录下存放脚本或者执行的时候指定日志文件)
[root@ubuntu ~]#cd /apps/nginx/logs/
#!/usr/bin/env python
#coding:utf-8
#Author:Yang Tao
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")      # 状态码为其他的打印ERROR
f.close()

print "200--:",len(status_200)   # 状态码200的有多少
print "404--:",len(status_404)   # 状态码400的有多少

# 测试脚本日志访问统计
[root@ubuntu logs]#python2.7 log.py 
 ERROR
 ERROR
 ERROR
 ERROR
 ERROR
 ERROR
 ERROR
 ERROR
 ERROR
 ERROR
 ERROR
 ERROR
 ERROR
 ERROR
 ERROR
 ERROR
200--: 135
404--: 36

Nginx 压缩功能

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

Nginx对文件的压缩功能是依赖于模块ngx_http_gzip_module,官方文档:
配置指令如下:

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

#压缩比由低到高从1到9,默认为1   (压缩比最好在5以下,3最好。压缩比太高太消耗带宽)
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 ...;
# 这个文件有很多压缩类型
[root@ubuntu logs]#vim /apps/nginx/conf/mime.types


#如果启用压缩,是否在响应报文首部插入“Vary: Accept-Encoding” (是否通知用户开启了压缩)
gzip_vary on | off;

mime.type文件作用介绍

  • 修改配置文件为压缩
[root@ubuntu ~]#vim /apps/nginx/conf/nginx.conf
http {
        gzip on;
        gzip_buffers 128 4k;
        gzip_comp_level 5;
        gzip_min_length 1k;
        gzip_types text/plain application/javascript application/x-javascript text/cssapplication/xml text/javascript application/x-httpd-php image/jpeg image/gif image/png;
        gzip_vary on;
     }
  • 准备测试文件
[root@ubuntu pc]#ll -h
total 108M
-rw-r--r-- 1 root root 108M Jan 11 17:11 messages.html
  • 测试压缩和不压缩区别
# 不压缩
[root@centos7 ~]#curl -I --compressed www.opengsd.net/messages.html
HTTP/1.1 200 OK
Server: nginx/1.16.1
Date: Sat, 11 Jan 2020 09:18:28 GMT
Content-Type: text/html; charset=utf-8
Content-Length: 113044372
Last-Modified: Sat, 11 Jan 2020 09:11:04 GMT
Connection: keep-alive
Keep-Alive: timeout=60
ETag: "5e199128-6bceb94"
Accept-Ranges: bytes

# 压缩
[root@centos7 ~]#curl -I --compressed www.opengsd.net/messages.html
HTTP/1.1 200 OK
Server: nginx/1.16.1
Date: Sat, 11 Jan 2020 09:18:57 GMT
Content-Type: text/html; charset=utf-8
Last-Modified: Sat, 11 Jan 2020 09:11:04 GMT
Connection: keep-alive
Keep-Alive: timeout=60
Vary: Accept-Encoding
ETag: W/"5e199128-6bceb94"
Content-Encoding: gzip   # 这里显示压缩

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.客户端解密信息:
客户端用之前生成的私钥获解密服务端传递过来的数据,由于数据一直是加密的,因此即使第三方获取到数据也无法知
道其详细内容。

ssl 配置参数

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

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

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

#当前虚拟主机使用的私钥文件,一般是key文件
ssl_protocols [SSLv2] [SSLv3] [TLSv1] [TLSv1.1] [TLSv1.2];

#支持ssl协议版本,早期为ssl,现在是TSL,默认为后三个
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

自签名 证书

#自签名CA证书
[root@s2 ~]# cd /apps/nginx/
[root@s2 nginx]# mkdir certs
[root@s2 nginx]# cd certs/
[root@s2 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 #国家代码,https://country-code.cl/
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) []:magedu.ca #通用名称
Email Address []:2973707860@qq.com #邮箱
[root@s2 certs]# ll ca.crt
-rw-r--r-- 1 root root 2118 Feb 22 12:10 ca.crt
#自制key和csr文件
[root@s2 certs]# openssl req -newkey rsa:4096 -nodes -sha256 -keyout www.magedu.net.key
-out www.magedu.net.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.net
Organizational Unit Name (eg, section) []:magedu.net
Common Name (eg, your name or your server's hostname) []:www.magedu.net
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@s2 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.net.csr
-rw-r--r-- 1 root root 3272 Feb 22 12:18 www.magedu.net.key
#签发证书
[root@s2 certs]# openssl x509 -req -days 3650 -in www.magedu.net.csr -CA ca.crt -CAkey
ca.key -CAcreateserial -out www.magedu.net.crt
Signature ok
subject=/C=CN/ST=BeiJing/L=BeiJing/O=magedu.net/OU=magedu.net/CN=www.magedu.net/emailAdd
ress=2973707860@qq.com
Getting CA Private Key
#验证证书内容
[root@s2 certs]# openssl x509 -in www.magedu.net.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.net, OU=magedu.net,
CN=www.magedu.net/emailAddress=2973707860@qq.com
        Subject Public Key Info:
                Public Key Algorithm: rsaEncryption
                Public-Key: (4096 bit)

Nginx证书配置

listen 80;
listen 443 ssl;
ssl_certificate /apps/nginx/certs/www.magedu.net.crt;
ssl_certificate_key /apps/nginx/certs/www.magedu.net.key;
ssl_session_cache shared:sslcache:20m;
ssl_session_timeout 10m;
#重启Nginx并访问验证

在这里插入图片描述

实现多域名HTTPS

Nginx支持基于单个IP实现多域名的功能,并且还支持单IP多域名的基础之上实现HTTPS,其实是基于Nginx的SNI(Server Name Indication)功能实现,SNI是为了解决一个Nginx服务器内使用一个IP绑定多个域名和证书的功能,其具体功能是客户端在连接到服务器建立SSL链接之前先发送要访问站点的域名(Hostname),这样服务器再根据这个域名返回给客户端一个合适的证书。

#制作key和csr文件
[root@s2 certs]# openssl req -newkey rsa:4096 -nodes -sha256 -keyout
mobile.magedu.net.key -out mobile.magedu.net.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
Organizational Unit Name (eg, section) []:magedu
Common Name (eg, your name or your server's hostname) []:mobile.magedu.net
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@s2 certs]# openssl x509 -req -days 3650 -in mobile.magedu.net.csr -CA ca.crt -
CAkey ca.key -CAcreateserial -out mobile.magedu.net.crt
Signature ok
subject=/C=CN/ST=BeiJing/L=BeiJing/O=magedu/OU=magedu/CN=mobile.magedu.net/emailAddress=
2973707860@qq.com
Getting CA Private Key
#验证证书内容
[root@s2 certs]# openssl x509 -in mobile.magedu.net.crt -noout -text
Certificate:
        Data:
                Version: 1 (0x0)
                Serial Number:
                        bb:76:ea:fe:f4:04:ac:07
        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 13:50:43 2019 GMT
                Not After : Feb 19 13:50:43 2029 GMT
        Subject: C=CN, ST=BeiJing, L=BeiJing, O=magedu, OU=magedu,
CN=mobile.magedu.net/emailAddress=2973707860@qq.com
        Subject Public Key Info:
                Public Key Algorithm: rsaEncryption
                        Public-Key: (4096 bit)
..............
#Nginx 配置
[root@s2 certs]# cat /apps/nginx/conf/conf.d/mobile.conf
server {
listen 80;
server_name mobile.magedu.net;
location / {
root html;
index index.html index.htm;
}
location /linux38 {
root /data/nginx/mobile/html;
index index.html index.htm;
}
location /python {
root /data/nginx/mobile/html;
index index.html index.htm;
}
}
server {
listen 443 ssl;
server_name mobile.magedu.net;
ssl_certificate /apps/nginx/certs/mobile.magedu.net.crt;
ssl_certificate_key /apps/nginx/certs/mobile.magedu.net.key;
ssl_session_cache shared:sslcache:20m;
ssl_session_timeout 10m;
location / {
root html;
index index.html index.htm;
}
location /linux38 {
root /data/nginx/mobile/html;
index index.html index.htm;
}
location /python {
root /data/nginx/mobile/html;
index index.html index.htm;
}
}

在这里插入图片描述

关于favicon.ico

favicon.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 90d; #设置文件过期时间
}

安全选项

隐藏Nginx版本号:

更改nginx源码信息并重新编译Nginx

# vim src/http/ngx_http_header_filter_module.c
49 static u_char ngx_http_server_string[] = "Server: linux38" CRLF; #定义响应报文中的
server字段信息

在这里插入图片描述

升级OpenSSL版本:

心脏出血(英语:Heartbleed),也简称为心血漏洞,是一个出现在加密程序库OpenSSL的安全漏洞,该程序库广泛用于实现互联网的传输层安全(TLS)协议。它于2012年被引入了软件中,2014年4月首次向公众披露。只要使用的是存在缺陷的OpenSSL实例,无论是服务器还是客户端,都可能因此而受到攻击。此问题的原因是在实现TLS的心跳扩展时没有对输入进行适当验证(缺少边界检查),因此漏洞的名称来源于“心跳”(heartbeat)。该程序错误属于缓冲区过读,即可以读取的数据比应该允许读取的还多。

准备OpenSSL源码包:
# pwd
/usr/local/src
# tar xvf openssl-1.1.1d
编译安装Nginx并制定新版本OpenSSL路径:
# cd /usr/local/src/nginx-1.16.1/
#./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 --withhttp_
gzip_static_module --with-pcre --with-stream --with-stream_ssl_module --withstream_
realip_module --with-select_module --with-file-aio --addmodule=/
usr/local/src/echo-nginx-module --with-openssl=/usr/local/src/openssl-1.1.1d
# make && make install
验证并启动Nginx:
# /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
# /apps/nginx/sbin/nginx

在这里插入图片描述

发表评论

0/200
9 点赞
0 评论
收藏
为你推荐 换一批