Nginx 學習筆記1--在web服務中的使用配置

I/O模型:

阻塞型、非阻塞型、復用型、信號驅動型、異步

  • 同步/異步:關注消息通知機制
  • 消息通知:
    • 同步:等待對方返回消息
    • 異步:被調用者通過狀態、通知或回調機制通知調用者被調用者的運行狀態
  • 阻塞/非阻塞:關注調用者在等待結果返回之前所處的狀態
    • 阻塞:blocking,調用結果返回之前,調用者被掛起;
    • 非阻塞:nonblocking,調用結果返回之前,調用者不會被掛起;
  • 一次文件IO請求,都會由兩個階段組成:
    第一步:等待數據,即數據從磁盤到內核內存
    第二步:復制數據,即數據內核內存到進程內存
    1. 阻塞型:第一步阻塞,第二步阻塞
    2. 非阻塞型: 第一步非阻塞,第二步阻塞
    3. 復用型:第一步阻塞,第二步阻塞;第一步阻塞在多路I/O上,調用內核復用器
    4. 信號驅動型:第一步完成后調用返回,非阻塞;第二步阻塞
    5. 異步:完全異步型I/O
  • 復用型IO調用
    • select(): 1024
    • poll(): 無限制
  • enent-driven:
    • epoll(linux):libevent
    • Kqueue(BSD):
    • /dev/poll (Solaris)

Nginx的程序架構:

  • master/worker

    • 一個master進程:負責加載和分析配置文件,管理worker進程,平滑升價
    • 一個或多個worker進程:處理并相應客戶請求
    • 緩存相關的進程:
      • cache loader:載入緩存對象
      • cache manager:管理緩存對象
  • 特性:異步、事件驅動和非阻塞

    • 并發請求處理:通過epoll/select
    • 文件IO:高級IO sendfile,異步,mmap
  • nginx模塊:高度模塊化,但其模塊早期不支持DSO機制;近期版本支持動態裝載和卸載;

    • 模塊分類:
      • 核心模塊:core module
      • 標準模塊:
        • HTTP module:
          • Standard HTTP modules
          • Optional HTTP modules
        • Mail modules
        • Stream modules: 傳輸層代理
        • 3rd party modules
  • nginx的功用:

    • 靜態的web資源服務器;(圖片服務器,或js/css/html/txt等靜態資源服務器);
    • 結合FastCGI/uwSGI/SCGI等協議反代動態資源請求;
    • http/https協議的反向代理;
    • imap4/pop3協議的反向代理;
    • tcp/udp協議的請求轉發;
nginx的安裝配置:
  • 官方的預制包:
    http://nginx.org/packages/centos/7/x86_64/RPMS/
    發行版的EPEL倉庫;

  • 編譯安裝:

          [root@localhos]# yum groupinstall "Development Tools" "Server Platform Development"
          [root@localhos]# yum install pcre-devel openssl-devel zlib-devel
          [root@localhos]# useradd -r nginx
          [root@localhos]# cd nginx-1.10.0
          [root@localhost nginx-1.10.0]#  ./configure --prefix=/usr/local/nginx --conf-path=/etc/nginx/nginx.conf --error-log-path=/var/log/nginx/error.log --http-log-path=/var/log/nginx/access.log --pid-path=/var/run/nginx.pid --lock-path=/var/run/nginx.lock --user=nginx --group=nginx --with-http_ssl_module --with-http_v2_module --with-http_dav_module --with-http_stub_status_module --with-threads --with-file-aio
          [root@localhos]# make && make install
    
  • 程序環境

    • 配置文件的組成部分:
      • 主配置文件:/etc/nginx/nginx.conf
      • include conf.d/*.conf
      • fastcgi,uwsgi,scgi等協議相關的配置文件
      • mime.types: 支持的mime類型;)多用途互聯網郵件擴展類型
    • 主程序文件:/usr/sbin/nginx
    • Unit File: nginx.service
  • 配置:

    • 主配置文件的配置指令:
      directive value [value2 ...];
    • 注意:
    1. 指令必須以分號結尾;
    2. 支持使用配置變量;
      • 內建變量:由Nginx模塊引入,可直接引用
      • 自定義變量:由用戶使用set命令定義;set variable_name value;
        - 引用變量:$variable_name
  • 主配置文件結構:

    main block : 主配置段,也即全局配置段
    event {
    ...
    } : 事件驅動相關的配置;
    http {
    ...
    } : http/httpd協議相關的配置段;
    mail {
    ...
    }
    stream {
    ...
    }

  • http協議相關的配置結構

      http{
          ...
          ...:各server的公共配置
          server {
              ...
          }:  每個server用于定義一個虛擬主機;
          server {
              ...
              listen
              server_name
              root
              alias
              location [OPERATOR] URL {
                  ...
                  if CONDITION {
                      ...
                      }
                  }
              }
          }
      
    
      示例:
      #在192.168.43.125的主機上添加server配置
      [root@localhost ~]# systemctl start nginx.service
      [root@localhost ~]# mkdir /data/nginx/vhost1 -pv
      [root@localhost ~]# vim /data/nginx/vhost1/index.html
          <h1>Nginx Vhosts</h1>
          <h2>192.168.43.125</h2>
      [root@localhost ~]# vim /etc/nginx/conf.d/vhost1.conf
      #在vhost1.conf文件中添加如下內容:
          server {
              listen 80;
              server_name www.ilinux.io;
              root /data/nginx/vhost1;
          }
      [root@localhost ~]# nginx -t     #檢查語法錯誤
      nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
      nginx: configuration file /etc/nginx/nginx.conf test is successfu
      [root@localhost ~]# nginx -s reload    #重載配置
    
      #使用另外的主機訪問此服務測試成功
      [root@localhost ~]# curl http://www.ilinux.io
      <h1>Nginx Vhosts</h1>
      <h2>192.168.43.125</h2>
    

Nginx(2)

配置指令:

  • main配置段常見的配置指令:
    分類:
    • 正常運行必備的配置
    • 優化性能相關的配置
    • 用于調試及定位問題相關的配置
    • 事件驅動相關的配置
一. 正常運行必備的配置:
  1. user:定義工作進程使用的用戶和組,如果省略組,則使用名稱等于用戶名的組。
  • syntax:user user [group];
  • Default: user nobody nobody;
  • Context: main
  1. pid /PATH/TO/PID_FILE:指定存儲nginx主進程進程號碼的文件路徑。
  2. include file | mask :指明包含進來的其他配置文件片段。
  3. load_module file:指明要裝載的動態模塊。
二. 性能優化相關的配置:
  1. worker_processes number | auto;
  • worker進程的數量;通常應該等于小于當前主機的cpu的物理核心數;
  • auto:當前主機物理cpu核心數;
  1. worker_cpu_affinity cpumask ...
  • worker_cpu_affinity auto [cpumask];
  • CPU MASK:
    • 00000000:表示8顆cpu核心
    • 00000001:0號cpu
    • 00000010:1號cpu
    • ... ...
  1. worker_priority number: 指定worker進程的nice值,設定worker進程的優先級;
  • 優先級范圍:[-20,20]
  1. worker_rlimit_nofile number: worker進程能夠打開的文件數量上限;
示例:
    [root@localhost ]# cd /etc/nginx/conf.d
    [root@localhost conf.d]# vim ../nginx.conf
        #在main配置文件中添加如下內容
        worker_cpu_affinity auto;
        worker_priority -5;
        worker_rlimit_nofile 65536;
    [root@localhost conf.d]# nginx -s reload
    [root@localhost conf.d]# watch 'ps axo comm,pid,psr | grep nginx'
        Every 0.5s: ps axo comm,pid,psr |grep nginx                                                     Sun Aug  5 21:04:58 2018

        nginx             5007   0
        nginx            10423   0
        nginx            10424   1
        nginx            10425   2
        nginx            10426   3
    #使用ab壓測www.ilinux.io/index.html
    [root@localhost ~]# ab -n 100000 -c 100 http://192.168.43.125/index.html
    [root@localhost conf.d]# ps axo comm,pid,psr,ni | grep nginx
        nginx             5007   0   0
        nginx            10423   0  -5
        nginx            10424   1  -5
        nginx            10425   2  -5
        nginx            10426   3  -5
三.調試、定位問題:
  1. daemon on | off:是否以守護進程方式運行Nginx;
  2. master_process on | off: 是否以master/worker模型運行nginx; 默認為on;
  3. error_log file [level];定義錯誤日志路徑與級別;
四.事件驅動相關的配置:
event {
    ...
}
  1. worker_connections number:每個worker進程所能打開的最大并發連接數量;
  • 總的最大并發響應數量:worker_reocesses*worker_connections
  1. use method:指明并發連接請求的處理方法
  • use epoll;
  1. accept——mutex on | off:處理新的連接請求的方法
  • on:意味著由各worker輪流處理新請求
  • off:意味著每個新請求的到達都會通知所有的worker進程

http協議相關的配置

一. 與套接字相關的配置
  1. server { ... } :配置一個虛擬主機

     server {
         listen address[:PORT]|PORT;
         server_name SERVER_NAME;
         root /PATH/TO/DOCUMENT_ROOT;                            
     }
    
  2. listen PORT | address[:port] | unix:/PATH/TO/SOCKET_FILE listen address[:port] [default_server] [ssl] [http2 | spdy] [backlog=number] [rcvbuf=size] [sndbuf=size] ;

  • default_server:設定為默認虛擬主機
  • ssl:限制僅能夠通過ssl連接提供服務
  • backlog=number:后援隊列長度
  • rcvbuf=size:接收緩沖區大小
  • sndbuf=size:發送緩沖區大小
  1. server_name name ...; 指明虛擬主機的名稱,后可根多個由空白字符分割的字符串;
  • 支持*通配任意長度的任意字符;例:server_name .magedu.com www.magedu.

  • 支持~起始的字符做正則表達式模式授權;例:server_name ~^www.\d+.magedu.com$

  • 匹配機制:

    • <1> 首先是字符串精確匹配;
    • <2> 左側*通配符;
    • <3> 右側*通配符;
    • <4> 正則表達式;

    練習:定義四個虛擬主機,混合使用三種類型的虛擬主機;僅開放給來自于本地網絡中的主機訪問;(開放給本地網絡中的主機把allow 后的IP地址改為網絡地址192.168.0.0/16即可)

            #在/etc/nginx/conf.d目錄下編輯配置文件
      [root@localhost conf.d]# vim vhost1.conf
          server {
              listen 80;
              server_name 192.168.43.125;
              root /data/nginx/vhost1;
              location / {
                  allow 192.168.43.143;
                  deny all;
              }
          }
          server {
              listen 80;
              server_name  www.ilinux.*;
              root /data/nginx/vhost1;
              location / {
                  allow 192.168.43.143;
                  deny all;
              }
          }
          server {
              listen 80;
              server_name ~^www\d+\.ilinux\.com$;
              root /data/nginx/vhost1;
              location / {
                  allow 192.168.0.0/16;
                  deny all;
              }
          }
          server { 
              listen 192.168.43.125:8080;
              server_name www3.ilinux.*;
              root /data/nginx/vhost2/;
              location / {
                  allow 192.168.43.143;
                  deny all;
              }
          }
    
  1. tcp_nodelay on | off;
  • 在keepalived模式下的連接是否啟用TCP_NODELAY選項;
  • delay:延遲發送;nodelay on:要求不要合并發送,請求一個發送一個;對非保持連接無效;
  1. tcp_nopush on | off
  • 在sendfile模式下,是否啟用TCP_CORK選項
  • nopush on :在一個包中發送響應頭和文件的開頭;以完整的包發送文件
  1. sendfile on | off;
  • 是否啟用sendfile 功能;
  • 系統調用sendfile()通過 DMA把硬盤數據拷貝到 kernel buffer,然后數據被 kernel直接拷貝到另外一個與 socket相關的 kernel buffer,這里沒有 user mode和 kernel mode之間的切換,在 kernel中直接完成了從一個 buffer到另一個 buffer的拷貝;DMA 把數據從 kernelbuffer 直接拷貝給協議棧,沒有切換,也不需要數據從 user mode 拷貝到 kernel mode,因為數據就在 kernel 里。步驟減少了,切換減少了,拷貝減少了,自然性能就提升了
二. 定義路徑相關的配置:
  1. root path
  • 設置web資源路徑映射;用于指明用戶請求的url所對應的本地文件系統上的文檔所在目錄路徑;
  • 可用的位置:http, server, location, if in location;
  1. location [ = | ~ | ~* | ^~ ] uri { ... }
  • 根據請求的URI設置配置

  • 在一個server中的location配置段可存在多個,用于實現從URI到文件系統的路徑映射;nginx會根據用戶請求的uri來檢查定義的所有location,并找出一個最佳匹配,而后應用其配置;

  • 匹配符:
    - = :對uri做精確匹配
    - ~: 對uri做正則表達式模式匹配,區分字符大小寫
    - ~*:對uri做正則表達式模式匹配,不區分字符大小寫
    - ^~: 對uri的左半部分做匹配檢查,不區分字符大小寫
    - 不帶符號:匹配起始于次uri的所有url

  • 匹配優先級:=,^,/~*,不帶符號;

      示例:
      #編輯配置文件
      [root@localhost ~]# vim /etc/nginx/conf.d/vhost1.conf 
              server {
              listen 80;
              server_name www.ilinux.io;
              root /data/nginx/vhost1;
              location / {
                      #root /data/nginx/vhost2;
                      allow all;
              }
              location ~*  \.(jpg|png)$ {
                      allow all;
              }
              location ^~ /images/ {
                      root /data/pictures/;
      #創建目錄
      [root@localhost ~]# mkdir -pv /data/pictures/images
      [root@localhost ~]# mv sky.jpg /data/pictures/images/
      #使用另外主機訪問測試,顯示正常如圖;
    
sky.png
  • 注意:在location /images/{}中的第一個/ 匹配/data/pictures/目錄;因此訪問www.ilinux.io/images/sky.jpg,即為/data/pictures/images/sky.jpg;

...

  1. alias path;
  • 定義路徑別名,文檔映射的另一種機制,僅能用于location上下文;

  • 注意:location中使用root指令和alias指令的意義不同
    - root,給定的路徑對應于location中的/uri/左側的/;
    - alias,給定的路徑對應于location中的/uri/右側的/;

      示例:
      #將上文配置中的location上下文中的root修改為alias即可
          location ^~ /images/ {
                  alias /data/pictures;
              }
      #復制圖片到/data/pictures目錄下訪問測試
      [root@localhost vhost1]# cp dice.jpg /data/pictures/
      #使用另外主機訪問測試如下圖所示
    
dice.png

...

  1. index file ...;
  • 默認資源;可用于http,server,location中。
  1. error_page code ... [=[response]] uri;
  • 定義錯誤顯示的URI

       示例:
       #修改配置文件
       [root@localhost ]# vim /etc/nginx/conf.d/vhost1.conf
           server {
              listen 80;
              server_name www.ilinux.io;
              root /data/nginx/vhost1;
              error_page 404 =200 /notfound.html;
              location / {
                      #root /data/nginx/vhost2;
                      allow all;
              }
              location ~*  \.(jpg|png)$ {
                      allow all;
              }
              location ^~ /images/ {
                       alias /data/pictures/;
              }
              location = /notfound.html {
                      root /data/nginx/error_pages;
              }
             }
             #創建目錄,和錯誤頁面信息
             [root@localhost ~]# mkdir /data/nginx/error_pages
             [root@localhost ~]# vim /data/nginx/error_pages/notfound.html
                 <h1>。。。。。。。</h1>
                  <h2> you are sha X</h2>
              [root@localhost ~]# nginx -s reload
    

使用另外的主機隨便訪問不存在的頁面測試如下圖

shaX.png
三. 定義客戶端請求的相關配置
  1. keepalive_timeout timeout [header_timeout];
  • 設定保持連接的超時時長,0表示禁止長連接;默認為75s;
  • Context: http, server, location
  1. keepalive_requests number;
  • 在一次長連接上所允許請求的資源最大數量,默認為100;
  • Context: http, server, location
  1. keepalive_disable none | browser ...;
  • 對哪種瀏覽器禁用長連接;
  • Context: http, server, location
  1. send_timeout time;
  • 向客戶端發送響應報文的超時時長,此處是指兩次寫操作之間的間隔時長;
  1. client_body_temp_path path [level1 [level2 [level3]]];
  • 設定用于存儲客戶端請求報文的body部分的臨時存儲路徑及子目錄結構和數量
  • 16進制的數字表示:client_body_temp_path /var/tmp/client_body 2 1 1
    • 2: 表示用2位16進制數字表示一級子目錄;00-ff
    • 1: 表示用1位16進制數字表示2級子目錄;0-f
    • 1:表示用1位16進制數字表示3級子目錄;0-f
四. 對客戶端進行限制的相關配置:
  1. limit_rate rate;
  • 限制響應給客戶端的傳輸速率,單位是bytes/second,0表示無限制;
  • Context: http, server, location, if in location
  1. limit_except method ... {...}
  • 限制對指定的請求方法之外的其它方法的使用客戶端;

    示例:
             limit_except GET {
             allow 192.168.1.0/24;
             deny all;
         }
         #除了GET和HEAD之外,其它所有的method都允許192.168.1.0/24網絡地址訪問,其它ip地址都拒絕;
    
五. 文件操作優化的配置
  1. aio on | off |threads[=pool];
  • 是否啟用aio功能;默認為off
  • Context: http, server, location
  1. directio size | off;
  • 在linux主機啟用O_DIRECT標記,此處意味文件大于等于給定的大小時使用,例如:directio 4m;
  1. open_file_cache off;
    open_file_cache max=N [inactive=time];
  • Configures a cache that can store;
  • nginx可以緩存以下三種信息:
    - <1> 文件的描述符、文件大小和最近一次的修改時間;
    - <2> 打開的目錄結構;
    - <3> 沒有找到的或者沒有權限訪問的文件的相關信息;
  • max=N: 可緩存的緩存項上限;達到上限后會使用LRU算法(最近最少使用)實現緩存管理;
  • inactive=time:緩存項的非活動時長,在此處指定的時長內未被命中的或命中的次數少于open_file_cache_min_uses指令所指定的次數的緩存項即為非活動項;
  1. open_file_cache_valid time;
  • 緩存項有效性的檢查頻率;默認為60s;
  1. open_file_cache_min_uses number;
  • 在open_file_cache指令的inactive參數指定的時長內,至少應該被命中多少次方可被歸類為活動項;
  1. open_file_cache_errors on|off;
  • 是否緩存查找時發生錯誤的文件一類的信息;
六. ngx_http_access_module模塊:實現基于ip的訪問控制功能
  1. allow address | CIDR | unix:| all;
  2. deny address | CIDR | unix | all;
  • 可用的位置:http,server,location,limit_except
七. ngx_http_auth_basic_module模塊:實現基于用戶的訪問控制,使用basic機制進行用戶認證;
  1. auth_basic string | off;
  • Default:auth_basic off;
  • Context: http, server, location, limit_except
  1. auth_basic_user_file file;
  • 注意:htpasswd命令由httpd-tools所提供;

      示例:
      [root@localhost ~]# yum -y install httpd-tools
      [root@localhost ~]# htpasswd -c -m /etc/nginx/.ngxpasswd tom
      New password: 
      Re-type new password: 
      Adding password for user tom
      #修改nginx配置文件
      [root@localhost ~]# vim /etc/nginx/conf.d/vhost1.conf 
      #在vhost1.conf配置中添加新的location,如下:
          location ~* ^/(admin|login) {
                  auth_basic "admin area or login url";
                  auth_basic_user_file /etc/nginx/.ngxpasswd; 
      #創建目錄和admin主頁
      [root@localhost ~]# mkdir /data/nginx/vhost1/admin
      [root@localhost ~]# vim /data/nginx/vhost1/admin/index.html
      [root@localhost ~]# nginx -t
      [root@localhost ~]# nginx -s reload
    

使用另外主機測試訪問:


auth_basic.png
八. ngx_http_stub_status_module模塊:用于輸出nginx的基本狀態信息
  1. stub_status;

    配置示例:
         [root@localhost ~]# vim /etc/nginx/conf.d/vhost1.conf 
             location ~* ^/(admin|login) {
                auth_basic "admin area or login url";
                auth_basic_user_file /etc/nginx/.ngxpasswd;
                stub_status;
            }
         [root@localhost ~]# nginx -s reload
    

訪問測試:


status.png
  • Active connections: 活動狀態的連接數;
  • accepts:已經接受的客戶端請求的總數;
  • handled:已經處理完成的客戶端請求的總數;
  • requests:客戶端發來的總的請求數;
  • Reading:處于讀取客戶端請求報文首部的連接的連接數;
  • Writing:處于向客戶端發送響應報文過程中的連接數;
  • Waiting:處于等待客戶端發出請求的空閑連接數;
九. ngx_http_log_module模塊:用于以指定的格式寫入請求日志
  1. log_format name string ...;
  • string 可以使用nginx核心模塊及其它模塊的內嵌變量
  • 注意:此配置只能用于http段中
  1. access_log path [format [buffer=size] [gzip=[level1]] [flush=time][if=condition]];
    access_log off;
  • 訪問日志文件路徑,格式及相關的緩沖的配置;
    - buffer=size: 設置日志緩沖區大小
    - flush=time:定義清空時長
  1. open_log_file_cache max=N [inactive=time] [min_uses=N] [valid=time];
    open_log_file_cache off;
  • 緩存各日志文件相關的元數據信息;

  • max:緩存的最大文件描述符數量;

  • min_uses:在inactive指定的時長內訪問大于等于此值方可被當作活動項;

  • inactive:非活動時長

  • valid:驗證緩存中各緩存項是否為活動項的時間間隔

    示例:為nginx定義使用類似于httpd的combined格式的訪問日志
      #在/etc/nginx/nginx.conf文件中http段配置日志格式
      [root@localhost ~]# vim /etc/nginx/nginx.conf
          http {
               log_format comd '$remote_addr - $remote_user [$time_local] '
                               '"$request" $status $bytes_sent '
                               '"$http_referer" "$http_user_agent"';
              ...
          }
      #給vhost1主機添加訪問日志,設置為comd格式
      [root@localhost ~]# vim /etc/nginx/conf.d/vhost1.conf
          server {
              ...
              access_log /var/log/nginx/vhost1-access.log comd;
              ...
          }   
      #訪問測試后查看日志格式
      [root@localhost ~]# tail -2 /var/log/nginx/vhost1-access.log 
      192.168.1.106 - tom [06/Aug/2018:23:18:27 +0800] "GET /images HTTP/1.1" 301 388 "-" "Mozilla/5.0 (X11; Linux x86_64; rv:45.0) Gecko/20100101 Firefox/45.0"
      192.168.1.106 - tom [06/Aug/2018:23:18:27 +0800] "GET /images/ HTTP/1.1" 403 324 "-" "Mozilla/5.0 (X11; Linux x86_64; rv:45.0) Gecko/20100101 Firefox/45.0"
    
十. ngx_http_gzip_module:用gzip格式壓縮響應;
  1. gzip on | off;
  • Enables or disables gzipping of responses.
  1. gzip_comp_level level;
  • Sets a gzip compression level of a response. Acceptable values are in the range from 1 to 9.
  1. gzip_disable regex ...;
  • Disables gzipping of responses for requests with “User-Agent” header fields matching any of the specified regular expressions.
  1. gzip_min_length length;
  • 啟用壓縮功能的響應報文大小閾值;
  1. gzip_buffers number size;
  • 支持實現壓縮功能時為其配置的緩沖區數量及每個緩存區的大小;
  1. gzip_proxied off | expired | no-cache | no-store | private | no_last_modified | no_etag | auth | any ...;
  • nginx作為代理服務器接收到從被代理服務器發送的響應報文后,在何種條件下啟用壓縮功能的;
  • off:對代理的請求不啟用
  • no-cache, no-store,private:表示從被代理服務器收到的響應報文首部的Cache-Control的值為此三者中任何一個,則啟用壓縮功能;
  1. gzip_types mime-type ...;
  • 壓縮過濾器,僅對此處設定的MIME類型的內容啟用壓縮功能;

      配置示例:   
      gzip  on;
      gzip_comp_level 6;
      gzip_min_length 64;
      gzip_proxied any;
      gzip_types text/xml text/css  application/javascript;   
    
  • 此配置可用位置:http, server, location

十一. ngx_http_ssl_module模塊:
  1. ssl on | off;
  • 是否啟用htttps協議
  1. ssl_certificate file;
  • 當前虛擬主機使用PEM格式的證書文件;
  1. ssl_certificate_key file;
  • 當前虛擬主機上與其證書匹配的私鑰文件;
  1. ssl_protocols [SSLv2] [SSLv3] [TLSv1] [TLSv1.1][TLSv1.2]
  • 支持ssl協議版本,默認為后三個;
  1. ssl_session_cache off | none | [builtin[:size]] [shared:name:size];
  • builtin[:size]:使用Openssl內建的緩存,此緩存為每worker進程私有;
  • [shared:name:size]:在各worker之間使用一個共享的緩存;
  1. ssl_session_timeout time;
  • 客戶端一側的連接可以服用ssl session cache中緩存的ssl參數的有效時長;

      配置示例:
          #創建私有CA自簽證書,以192.168.1.106為CA
          [root@localhost CA]# mkdir /etc/pki/CA/{private,certs,crl,newcerts} -pv
          [root@localhost CA]# cd /etc/pki/CA
          [root@localhost CA]# (umask 077; openssl genrsa -out private/cakey.pem 2048)
          [root@localhost CA]# openssl req -new -x509 -key private/cakey.pem -out cacert.pem -days 365
          ...
          -----
          Country Name (2 letter code) [XX]:CN
          State or Province Name (full name) []:SD
          Locality Name (eg, city) [Default City]:JN
          Organization Name (eg, company) [Default Company Ltd]:ilinux.com
          Organizational Unit Name (eg, section) []:opt
          Common Name (eg, your name or your server's hostname) []:www.ilinux.com
          [root@localhost CA]# touch index.txt
          [root@localhost CA]# echo 01 > serial
          #在nginx主機上生成私鑰和申請證書
          [root@www1 ~]# (umask 077;openssl genrsa -out /etc/nginx/ssl/.nginx.key 2048)
          [root@www1 ~]# openssl req -new -key /etc/nginx/ssl/.nginx.key -out /etc/nginx/ssl/nginx.crs -days 365
          [root@www1 ~]# scp /etc/nginx/ssl/nginx.crs root@192.168.1.106:/tmp
          #在CA上簽署證書
          [root@localhost CA]# openssl ca -in /tmp/nginx.crs -out certs/nginx.crt -days 365
          #把簽署好的證書nginx.crt傳會nginx主機
          [root@localhost CA]# scp certs/nginx.crt root@192.168.1.105:/etc/nginx/ssl
          root@192.168.1.105's password: 
          #修改nginx配置文件,啟用ssl
          [root@www1 ~]# vim /etc/nginx/conf.d/vhost1.conf
              server {
                  listen 443 ssl;
                  server_name www1.ilinux.com;
                  root /data/nginx/vhost1;
                  index index.html
                  error_page 404 =200 /notfound.html;
                  access_log /var/log/nginx/vhost1-access.log comp;
                  ssl on;
                  ssl_certificate /etc/nginx/ssl/nginx.crt;
                  ssl_certificate_key /etc/nginx/ssl/.nginx.key;
                  ssl_protocols sslv2 sslv3 tlsv1 tlsv1.1 tlsv1.2;
                  ssl_session_cache shared:SSL:10m;
                  location / {
                      root /data/nginx/vhost2;
                      deny 192.168.1.108;
                      allow all;
                      }
                  location ~*.(jpg|png)$ {
                      deny 192.168.1.107;
                      allow all;
                      }
                  location ^~ /images/ {
                      alias /data/pictures/;
                      allow all;
                      }
                  location  /notfound.html {
                      root /data/nginx/error_pages;
                      }
                  location ~* ^/(admin|login) {
                      auth_basic "admin area or login url";
                      auth_basic_user_file /etc/nginx/.ngxpasswd;
                      index flower.jpg;
                      }
                  location /ngxstatus/ {
                      stub_status;
                      auth_basic ngxstatus;
                      auth_basic_user_file /etc/nginx/.ngxpasswd;
                      }
                  }
          #檢查語法,重載配置
          [root@www1 ~]# nginx -t
          nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
          nginx: configuration file /etc/nginx/nginx.conf test is successful
          [root@www1 ~]# nginx -s reload
    

使用外部主機訪問測試:


ssl1.png
喪失了.png
十二. ngx_http_rewrite_module模塊:

-將用戶請求的URI基于regex所描述的模式進行檢查,然后完成替換;

  1. rewrite regex replacement [flag]
    將用戶請求的URI基于regex所描述的模式進行檢查,匹配到時將其替換為replacement指定的新的URI;
  • 注意:如果在同一級配置塊中存在多個rewrite規則,那么會自下而上逐個檢查;被某條件規則替換完成后,會重新一輪的替換檢查,因此,隱含有循環機制;[flag]所表示的標志位用于控制此循環機制;
  • 如果replacement是以http://或https://開頭,則替換結果會直接以重定向返回給客戶端;301:永久重定向;
  • [flag]:
    • last:重寫完成后停止對當前URI在當前location中后續的其他重寫操作,而后對新的URI啟動新的一路重寫檢查;提前重啟新一輪循環;
    • break:重寫完成后停止對當前URI在當前location中后續的其他重寫操作,而后直接跳轉至重寫規則配置塊之后的其他配置;循環結束;
    • redirect:重寫完成后以臨時重定向方式直接返回重寫后生成的新URI給客戶端,有客戶端重新發起請求;不能以http://或https://開頭;
    • permanent:重寫完成后以永久重定向方式直接返回重寫后生成的新URI給客戶端,由客戶端重新發起請求;
  1. return
  • 停止處理并將指定的代碼返回給客戶端

    return code [text];
    return code URL;
    return URL;

  1. rewrite_log on |off;
  • 是否開啟重寫日志
  1. if (condition) {...}
  • 引入一個新的配置上下文:條件滿足是,執行配置塊中的配置指令;

  • 可用于server和location段中

    condition:
    比較操作符:
    ==
    !=
    ~:模式匹配,區分字符大小寫
    ~:模式匹配,區分字符大小寫
    !~:模式不匹配,區分字符大小寫
    !~
    :模式不匹配,不區分字符大小寫
    文件及目錄存在性判斷:
    -e, !-e
    -f, !-f
    -d, !-d
    -x, !-x

  1. set $variable value
  • 用戶自定義變量

    簡單示例:
    #重新編輯配置文件vhost.conf
    [root@www1 conf.d]# vim vhost.conf

          server {
          listen 80;
          server_name www.ilinux.com;
          root /data/nginx/vhost1;
          rewrite /(.*)\.png$ /$1.jpg;
          }
      [root@www1 conf.d]# nginx -s reload
    

訪問測試.png能否重寫為.jpg

day.png

十三. ngx_http_referer_module模塊:
  • The ngx_http_referer_module module is used to block access to a site for requests with invalid values in the “Referer” header field.
  1. valid_referers none | blocked | server_names | string ...;
    • 定義referer首部的合法引用用值;

                none:請求報文首部沒有referer首部;
                blocked:請求報文的referer首部沒有值;
                server_names:參數,其可以有值作為主機名或主機名模式;
                    arbitrary_string:直接字符串,但可使用*作通配符;
                    regular expression:被指定的正則表達式模式匹配到的字符串;要使用~打頭,例如 ~.*\.magedu\.com;
                    $invalid_referer : 模塊內置變量,非法引用,只要沒被valid_referers定義匹配到的就是非法引用
      

...

    配置示例:
                valid_referers none block server_names *.magedu.com *.mageedu.com magedu.* mageedu.* ~\.magedu\.;
                
                if($invalid_referer) {
                    return http://www.magedu.com/invalid.jpg;
                }
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容