Nginx高階用法(一)


Nginx 狀態頁

  基於nginx模塊ngx_http_auth_basic_module實現,在編譯安裝nginx的時候需要添加編譯參數--with-http_stub_status_module,否則配置完成之後監測會是提示語法錯誤。

查看是否加載了ngx_http_auth_basic_module模塊
[root@CentOS7 ~]#/apps/nginx/sbin/nginx -V
nginx version: nginx/1.14.2
built by gcc 4.8.5 20150623 (Red Hat 4.8.5-36) (GCC)
built with OpenSSL 1.0.2k-fips  26 Jan 2017
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 --with-http_perl_module
[root@CentOS7 ~]#vim /apps/nginx/conf/nginx.conf
        location /nginx_status {
                stub_status;
                allow 192.168.36.0/24;
                deny all;
        }

[root@CentOS7 ~]#/apps/nginx/sbin/nginx -s reload

訪問測試

[root@CentOS-Test ~]#curl 192.168.36.104/nginx_status
Active connections: 1
server accepts handled requests
 124 124 223  # 這三個數字分別對應accepts,handled,requests三個值
Reading: 0 Writing: 1 Waiting: 0

Active connections: 當前處於活動狀態的客戶端連接數,包括連接等待空閒連接數。
accepts:統計總值,Nginx自啓動後已經接受的客戶端請求的總數。
handled:統計總值,Nginx自啓動後已經處理完成的客戶端請求的總數,通常等於accepts,除非有因
worker_connections限制等被拒絕的連接。
requests:統計總值,Nginx自啓動後客戶端發來的總的請求數。
Reading:當前狀態,正在讀取客戶端請求報文首部的連接的連接數。
Writing:當前狀態,正在向客戶端發送響應報文過程中的連接數。
Waiting:當前狀態,正在等待客戶端發出請求的空閒連接數,開啓 keep-alive的情況下,這個值等於active – (reading+writing),

Nginx第三方模塊

添加第三方模塊:echo-nginx-module
[root@CentOS7 ~]#yum install git -y
[root@CentOS7 ~]#git clone https://github.com/openresty/echo-nginx-module.git
[root@CentOS7 ~]#cd nginx-1.14.2/
[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 \
> --with-http_perl_module \
> --add-module=/root/echo-nginx-module  # 添加echo模塊

[root@CentOS7 nginx-1.14.2]#make && make install  # make安裝
[root@CentOS7 ~]#vim /apps/nginx/conf.d/pc.conf
[root@CentOS7 ~]#cat /apps/nginx/conf.d/pc.conf
server {
  listen 80;
  server_name www.darius.com;
  error_log logs/www_darius_com_error.log;
  access_log logs/www_darius_com_access.log;
  location /main {
    index index.html;
    default_type text/html;
    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@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@CentOS7 ~]#curl www.darius.com/main
sub1
sub2
took 2.008 sec for total.

Nginx變量使用

nginx的變量可以在配置文件中引用,作爲功能判斷或者日誌等場景使用,變量可以分爲內置變量和自定義變量,內置變量是由nginx模塊自帶,通過變量可以獲取到衆多的與客戶端訪問相關的值。

內置變量

$remote_addr;
# 存放了客戶端的地址,注意是客戶端的公網IP,也就是一家人訪問一個網站,則會顯示爲路由器的公網IP。
$args;
# 變量中存放了URL中的指令,例如http://www.darius.com/main/index.do?
id=20190221&partner=search中的id=20190221&partner=search
$document_root;
# 保存了針對當前資源的請求的系統根目錄,如/apps/nginx/html
$document_uri;
# 保存了當前請求中不包含指令的URI,注意是不包含請求的指令,比如
http://www.darius.com/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;
# 請求的服務器的端口號

自定義變量

假如需要自定義變量名稱和值,使用指令set $variable value;,則方法如下:

set $name magedu;
echo $name;
set $my_port $server_port;
echo $my_port;
echo "$server_name:$server_port";

範例

1、查看Nginx內置變量

[root@CentOS7 ~]#vim /apps/nginx/conf.d/pc.conf
[root@CentOS7 ~]#cat /apps/nginx/conf.d/pc.conf
server {
  listen 80;
  server_name www.darius.com;
  error_log logs/www_darius_com_error.log;
  access_log logs/www_darius_com_access.log;
  location /main {
    index index.html;
    default_type text/html;
    echo $request_uri;
  }
}
[root@CentOS7 ~]#/apps/nginx/sbin/nginx -s reload
[root@CentOS7 ~]#curl www.darius.com/main
/main
[root@CentOS7 ~]#curl www.darius.com/main/xxx
/main/xxx

2、查看Nginx自定義變量

[root@CentOS7 ~]#vim /apps/nginx/conf.d/pc.conf
[root@CentOS7 ~]#cat /apps/nginx/conf.d/pc.conf
server {
  listen 80;
  server_name www.darius.com;
  error_log logs/www_darius_com_error.log;
  access_log logs/www_darius_com_access.log;
  location /main {
    index index.html;
    default_type text/html;
    set $name Darius;
    echo $name;
  }
}
[root@CentOS7 ~]#/apps/nginx/sbin/nginx -s reload
[root@CentOS7 ~]#curl www.darius.com/main
Darius

自定義Nginx訪問日誌

訪問日誌是記錄客戶端即用戶的具體請求內容信息,全局配置模塊中的error_log是記錄nginx服務器運行時的日誌保存路徑和記錄日誌的level,因此有着本質的區別,而且Nginx的錯誤日誌一般只有一個,但是訪問日誌可以在不同server中定義多個,定義一個日誌需要使用access_log指定日誌的保存路徑,使用log_format指定日誌的格式,格式中定義要保存的具體日誌內容。

默認的日誌格式

    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;

自定義json格式日誌

[root@CentOS7 ~]#vim /apps/nginx/conf/nginx.conf
    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@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

訪問測試
Nginx高階用法(一)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章