专栏名称: 马哥Linux运维
马哥linux致力于linux运维培训,连续多年排名第一,订阅者可免费获得学习机会和相关Linux独家实战资料!
目录
相关文章推荐
51好读  ›  专栏  ›  马哥Linux运维

3W字长文讲透Nginx高阶用法

马哥Linux运维  · 公众号  · 运维  · 2019-12-26 21:00

正文

请到「今天看啥」查看全文



'"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@CentOS7 ~]#/apps/nginx/sbin/nginx -s reload

[root@CentOS7 ~]#tail -f /apps/nginx/logs/access_json.log
{"@timestamp":"2019-05-30T18:58:23+08:00","host":"192.168.36.104","clientip":"192.168.36.110","size":15,"responsetime":0.000,"upstreamtime":"-","upstreamhost":"-","http_host":"192.168.36.104","uri":"/index.html","domain":"192.168.36.104","xff":"-","referer":"-","tcp_xff":"","http_user_agent":"curl/7.29.0","status":"200"}

python实现json格式的日志访问统计

[root@CentOS7 logs]#cat nginx_json.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")
f.close()
print "状态码200的有--:",len(status_200)
print "状态码404的有--:",len(status_404)

# 保存日志文件到指定路径并进测试:
[root@CentOS7 ~]# python nginx_json.py
....
状态码200的有--: 403428
状态码404的有--: 125712

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;

配置文件修改

    gzip on;
gzip_comp_level 5;
gzip_min_length 1;
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@CentOS7 ~]#/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@CentOS7 ~]#/apps/nginx/sbin/nginx -s reload

访问测试

[root@CentOS-Test ~]#curl --head --compressed http://www.darius.com/test1.html
HTTP/1.1 200 OK
Server: nginx
Date: Thu, 30 May 2019 11:26:49 GMT
Content-Type: text/html
Last-Modified: Thu, 30 May 2019 11:26:31 GMT
Connection: keep-alive
Vary: Accept-Encoding
ETag: W/"5cefbde7-720"
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开启

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@CentOS7 ~]#cd /apps/nginx/
[root@CentOS7 nginx]#mkdir certs
[root@CentOS7 nginx]# cd certs/
[root@CentOS7 certs]#openssl req -newkey rsa:4096 -nodes -sha256 -keyout ca.key -x509 -days 3650 -out ca.crt # 自签名CA证书
Generating a 4096 bit 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]:magedu.com # 公司名称
Organizational Unit Name (eg, section) []:magedu # 部门
Common Name (eg, your name or your server's hostname) []:M36 # 通用名称
Email Address []: # 邮箱
[root@CentOS7 certs]#ll ca.crt
-rw-r--r-- 1 root root 2009 5月 30 19:34 ca.crt

# 创建自定义额key和csr文件

[root@CentOS7 certs]#openssl req -newkey rsa:4096 -nodes -sha256 -keyout www.darius.com.key -out www.darius.com.csr
Generating a 4096 bit RSA private key
............++
..........................++
writing new private key to '
www.darius.com.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]:magedu.com
Organizational Unit Name (eg, section) []:magedu
Common Name (eg, your name or your server'
s hostname) []:M36
Email Address []:

Please enter the following 'extra' attributes
to be sent with your certificate request
A challenge password []:
An optional company name []:

[root@CentOS7 certs]#ll
总用量 16
-rw-r--r-- 1 root root 2009 5月 30 19:34 ca.crt
-rw-r--r-- 1 root root 3272 5月 30 19:34 ca.key
-rw-r--r-- 1 root root 1695 5月 30 19:38 www.darius.com.csr
-rw-r--r-- 1 root root 3272 5月 30 19:38 www.darius.com.key

# 证书签发
[root@CentOS7 certs]#openssl x509 -req -days 3650 -in www.darius.com.csr -CA ca.crt -CAkey ca.key -CAcreateserial -out www.darius.com.crt
Signature ok
subject=/C=CN/ST=BeiJing/L=BeiJing/O=magedu.com/OU=magedu/CN=M36
Getting CA Private Key

验证证书内容
[root@CentOS7 certs]#openssl x509 -in www.darius.com.crt -noout -text
Certificate:
Data:
Version: 1 (0x0)
Serial Number:
fe:15:2c:1a:9d:a5:df:f5
Signature Algorithm: sha256WithRSAEncryption
Issuer: C=CN, ST=BeiJing, L=BeiJing, O=magedu.com, OU=magedu, CN=M36
Validity
Not Before: May 30 11:42:02 2019 GMT
Not After : May 27 11:42:02 2029 GMT
Subject: C=CN, ST=BeiJing, L=BeiJing, O=magedu.com, OU=magedu, CN=M36
Subject Public Key Info:
Public Key Algorithm: rsaEncryption
Public-Key: (4096 bit)

修改Nginx配置文件

[root@CentOS7 ~]#vim /apps/nginx/conf.d/pc.conf
[root@CentOS7 ~]#cat /apps/nginx/conf.d/pc.conf
server {
listen 80;
listen 443 ssl;
ssl_certificate /apps/nginx/certs/www.darius.com.crt;
ssl_certificate_key /apps/nginx/certs/www.darius.com.key;
ssl_session_cache shared:sslcache:20m;
ssl_session_timeout 10m;
server_name www.darius.com;
error_log logs/www_darius_com_error.log;
access_log logs/www_darius_com_access.log;
location / {
index index.html;
root /data/nginx/html/pc;
}
}

[root@CentOS7 ~]#/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@CentOS7 ~]#/apps/nginx/sbin/nginx -s reload

访问测试

关于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/images123;
}

显示效果

修改Nginx Server版本信息

# 修改Nginx源码文件,此配置文件需要在nginx.conf的http中添加server_tokens  off;开启nginx版本隐藏才能实现预期效果
[root@CentOS7 nginx-1.14.2]#vim src/http/ngx_http_header_filter_module.c
49 static u_char ngx_http_server_string[] = "Server: Darius/10.0" CRLF;

# 停止Nginx服务,重新编译Nginx
[root@CentOS7 nginx-1.14.2]#/apps/nginx/sbin/nginx -s stop
[root@CentOS7 nginx-1.14.2]#./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=/root/echo-nginx-module

[root@CentOS7 nginx-1.14.2]#make && make ×××tall

启动服务
[root@CentOS7 nginx-1.14.2]#/apps/nginx/sbin/nginx






请到「今天看啥」查看全文