32-高性能WEB服務(wù)NGINX(二)

選擇SSL證書品牌(CA供應(yīng)商)

  • 阿里云SSL證書申請:
    https://www.aliyun.com/product/cas?spm=a2c4g.11174283.2.1.47676fd4baNCYX
  • 支持阿里云頒發(fā)數(shù)字證書的安全CA中心包括:
    ● Symantec:賽門鐵克(Symantec)是全球第一大數(shù)字證書頒發(fā)機(jī)構(gòu)、全球最值得信賴的SSL證書品牌,所有證書都采用業(yè)界領(lǐng)先的加密技術(shù)余素,為不同的網(wǎng)站和服務(wù)器提供安全解決方案
    ● CFCA: 中國金融認(rèn)證中心(CFCA)通過國際WebTrust認(rèn)證闻鉴,遵循全球統(tǒng)一鑒證標(biāo)準(zhǔn),是國際CA瀏覽器聯(lián)盟組織成員芒篷。 CFCA全球信任SSL證書搜变,由中國權(quán)威數(shù)字證書認(rèn)證機(jī)構(gòu)自主研發(fā),純國產(chǎn)證書针炉。 CFCA提供 7x24 小時(shí)金融級的安全保障服務(wù)痹雅,且有完善的風(fēng)險(xiǎn)承保計(jì)劃。提供中文版全球信任體系電子認(rèn)證業(yè)務(wù)規(guī)則(CPS)糊识,便于用戶理解雙方權(quán)利和義務(wù)
    ● GeoTrust: GeoTrust 是全球第二大數(shù)字證書頒發(fā)機(jī)構(gòu)绩社, 也是身份認(rèn)證和信任認(rèn)證領(lǐng)域的領(lǐng)導(dǎo)者,采用各種先進(jìn)的技術(shù)使任何大小的機(jī)構(gòu)和公司都能安全赂苗、低成本地部署SSL數(shù)字證書和實(shí)現(xiàn)各種身份認(rèn)證
    ● GlobalSign: GMO GlobalSign是全球最早的數(shù)字證書認(rèn)證機(jī)構(gòu)之一愉耙,一直致力于網(wǎng)絡(luò)安全認(rèn)證及數(shù)字證書服務(wù),是一個(gè)備受信賴的CA和SSL數(shù)字證書提供商

選擇證書類型

  • 阿里云聯(lián)合有資質(zhì)的CA中心推薦以下幾種數(shù)字證書配置組合方案:

  • 免費(fèi)型DV SSL: 免費(fèi)型DV SSL證書是基礎(chǔ)級SSL產(chǎn)品
    ● 說明 目前僅Symantec提供免費(fèi)型數(shù)字證書拌滋,該證書僅支持綁定一個(gè)域名
    ● 只驗(yàn)證域名所有權(quán)朴沿,數(shù)小時(shí)內(nèi)即可頒發(fā)
    ● 只提供通信鏈路加密功能
    ● 根證書一般使用CA中心認(rèn)證的根證書
    ● 支持綁定一個(gè)明細(xì)子域名,且不支持通配符域名

  • 通配符DV SSL:通配符DV SSL證書屬于DV型SSL證書(Domain Validation SSL)
    ● 只驗(yàn)證域名所有權(quán)败砂,數(shù)小時(shí)內(nèi)即可頒發(fā)
    ● 提供高強(qiáng)度通信鏈路加密功能
    ● 支持綁定一個(gè)帶有通配符的域名

  • 專業(yè)版OV SSL: 專業(yè)版OV SSL證書屬于OV型SSL證書(Organization Validation SSL)
    ● 驗(yàn)證域名所有權(quán)和申請單位的真實(shí)身份赌渣,解決在線信任問題
    ● 證書中顯示申請者的企業(yè)單位名稱,讓訪問用戶安心使用
    ● 提供高強(qiáng)度通信鏈路加密功能
    ● 支持最多綁定100個(gè)域名昌犹,支持綁定通配符域名
    ● 說明 除專業(yè)版OV SSL證書外坚芜,Symantec還提供增強(qiáng)型OV SSL證書。增強(qiáng)型OV SSL證書采用ECC橢圓曲線算法

  • 高級版EV SSL:高級版EV SSL證書屬于EV型SSL證書(Extended Validation SSL)
    ● 嚴(yán)格驗(yàn)證域名所有權(quán)和申請單位的真實(shí)身份
    ● 證書在大部分瀏覽器中能顯示綠色地址欄(部分證書在Safari瀏覽器中不顯示)斜姥,有效解決在線信任和網(wǎng)站被假冒問題
    ● 證書中詳細(xì)顯示申請者的企業(yè)單位信息鸿竖,讓訪問用戶安心使用
    ● 提供高強(qiáng)度通信鏈路加密功能。
    ● 支持最多綁定100個(gè)域名
    ● 說明 除高級版EV SSL證書外铸敏,Symantec還提供增強(qiáng)型EV SSL證書缚忧。增強(qiáng)型EV SSL證書采用ECC橢圓曲線算法

ngx_http_ssl_module

  • ssl on | off;
    為指定虛擬機(jī)啟用HTTPS protocol, 建議用listen指令代替

  • ssl_certificate file;
    當(dāng)前虛擬主機(jī)使用PEM格式的證書文件

  • ssl_certificate_key file;
    當(dāng)前虛擬主機(jī)上與其證書匹配的私鑰文件

  • ssl_protocols [SSLv2] [SSLv3] [TLSv1] [TLSv1.1] [TLSv1.2]; 支持ssl協(xié)議版本杈笔,默認(rèn)為后三個(gè)

  • ssl_session_cache off | none | [builtin[:size]] [shared:name:size];
    none: 通知客戶端支持ssl session cache闪水,但實(shí)際不支持
    builtin[:size]:使用OpenSSL內(nèi)建緩存,為每worker進(jìn)程私有
    [shared:name:size]:在各worker之間使用一個(gè)共享的緩存

  • ssl_session_timeout time;
    客戶端連接可以復(fù)用ssl session cache中緩存的有效時(shí)長蒙具,默認(rèn)5m

示例:

server {
    listen 443 ssl;
    server_name www.magedu.com;
    root /vhosts/ssl/htdocs;
    ssl on;
    ssl_certificate /etc/nginx/ssl/nginx.crt;
    ssl_certificate_key /etc/nginx/ssl/nginx.key;
    ssl_session_cache shared:sslcache:20m;
    ssl_session_timeout 10m;
}  

小筆記:nginx ssl

#生成cA證書
cd /etc/pki/tls/certs
make magedu.crt
password            #默認(rèn)得輸密碼
CN
beijing
beijing
magedu.net
opt
www.magedu.net

openssl rsa -in magedu.key -out magedu.net.key      #解密私鑰
mv magedu.crt magedu.net.crt
chomod 600 magedu.net.key
mv magedu.net.crt magedu.net.key /etc/nginx/ssl

vim /etc/nginx/conf.d/test.conf
server {
    server_name www.magedu.net;
    root /data/test;
    location / {}
    access_log /var/log/nginx/magedu_net.access.log access_json;
    gzip on;                #啟用壓縮
    gzip_comp_level 6;      #壓縮等級
    gzip_min_length 64;     #響應(yīng)報(bào)文閾值
    gzip_vary on;           #響應(yīng)報(bào)文首部插入“Vary: Accept-Encoding”  
    gzip_types text/xml text/css application/javascript;    #壓縮類型
}
server {
    listen 443 ssl;
    server_name www.magedu.net;
    root /data/test;
    ssl_certificate /etc/nginx/ssl/magedu.net.crt;
    ssl_certificate_key /etc/nginx/ssl/magedu.net.key;
    ssl_session_cache shared:sslcache:20m;
    ssl_session_timeout 10m;
    access_log /var/log/nginx/magedu_net.ssl.access.log access_json;
}

vim /etc/nginx/conf.d/test.conf             #一個(gè)虛擬主機(jī)
server {
    listen 80;
    listen 443 ssl;
    server_name www.magedu.net;
    root /data/test;
    ssl_certificate /etc/nginx/ssl/magedu.net.crt;
    ssl_certificate_key /etc/nginx/ssl/magedu.net.key;
    ssl_session_cache shared:sslcache:20m;
    ssl_session_timeout 10m;
    access_log /var/log/nginx/magedu_net.ssl.access.log access_json;
}

ngx_http_rewrite_module

  • ngx_http_rewrite_module模塊:
    將用戶請求的URI基于PCRE regex所描述的模式進(jìn)行檢查球榆,而后完成重定向替換
    示例:
    http://www.magedu.com/hn --> http://www.magedu.com/henan
    http://www.magedu.com --> https://www.magedu.com/

  • if (condition) { ... }
    條件滿足時(shí)峰弹,執(zhí)行配置塊中的配置指令;server, location
    condition:

    比較操作符:
      = 相同 != 不同
      ~ 模式匹配芜果,區(qū)分字符大小寫
      ~* 模式匹配鞠呈,不區(qū)分字符大小寫
      !~ 模式不匹配,區(qū)分字符大小寫
      !~* 模式不匹配右钾,不區(qū)分字符大小寫
    文件及目錄存在性判斷:
      -e蚁吝,!-e 存在與否(包括文件,目錄舀射,軟鏈接)
      -f窘茁,!-f 文件 -d,!-d 目錄 -x脆烟,!-x 執(zhí)行
    
  • 注意: if (condition) { ... } 語句中山林,如果$變量的值為空字符串或是以0開頭的任意字符串,則 if 指令認(rèn)為該條件為false邢羔,其它條件為true
    示例:

    location /test {
      index index.html;
      default_type text/html;
      if ( $scheme = http ){
          return 301 https://www.magedu.net/;
      }
      if ( $scheme = https ){
          echo "if ----> $scheme";
      } 
      if (-f $request_filename) {
          echo "file is exist";
      }
      if (!-f $request_filename) {
          echo "file is not exist";
          return 409;
      }
    } 
    
  • return
    return code [text]; #返回客戶端指定的狀態(tài)碼和文本說明
    return code URL;
    return URL;
    停止處理驼抹,并返回給客戶端指定的響應(yīng)碼(包括: 204, 400, 402 — 406, 408,410, 411, 413, 416, 500 — 504),并對 301, 302, 303, 307, 308跳轉(zhuǎn)到URL

  • rewrite_log on | off;
    是否開啟重寫日志, 發(fā)送至error_log(notice level)

  • set variable value; 用戶自定義變量 注意:變量定義和調(diào)用都要以開頭

    示例:

    location /test {
      root /data/nginx/html/pc;
      default_type text/html;
      index index.html;
      if ( $scheme = http ){
          #return 666;
          #return 666 "not allow http";
          #return 301 http://www.baidu.com;
          return 500 "service error";
          echo "if-----> $scheme"; #return后面的將不再執(zhí)行
      }
      if ( $scheme = https ){
          echo "if ----> $scheme";
      }
    } 
    
  • rewrite regex replacement [flag]
    ● 將用戶請求的URI基于regex所描述的模式進(jìn)行檢查拜鹤,匹配到時(shí)將其替換為replacement指定的新的URI
    ● 注意:如果在同一級配置塊中存在多個(gè)rewrite規(guī)則框冀,那么會(huì)自下而下逐個(gè)檢查;被某條件規(guī)則替換完成后敏簿,會(huì)重新一輪的替換檢查
    ● 隱含有循環(huán)機(jī)制,但不超過10次明也;如果超過,提示500響應(yīng)碼惯裕,[flag]所表示的標(biāo)志位用于控制此循環(huán)機(jī)制
    ● 如果replacement是以http://或https://開頭温数,則替換結(jié)果會(huì)直接以重向返回給客戶端, 即永久重定向301

  • [flag]:
    ● last:重寫完成后停止對當(dāng)前URI在當(dāng)前l(fā)ocation中后續(xù)的其它重寫操作,而后對新的URI啟動(dòng)新一輪重寫檢查蜻势;提前重啟新一輪循環(huán)
    ● break:重寫完成后停止對當(dāng)前URI在當(dāng)前l(fā)ocation中后續(xù)的其它重寫操作撑刺,而后直接跳轉(zhuǎn)至重寫規(guī)則配置塊后的其它配置;結(jié)束循環(huán)
    ● redirect:臨時(shí)重定向咙边,重寫完成后以臨時(shí)重定向方式直接返回重寫后生成的新URI給客戶端猜煮,由客戶端重新發(fā)起請求;可使用相對路徑,或http://或https://開頭败许,此重定向信息不可緩存,狀態(tài)碼:302
    ● permanent:重寫完成后以永久重定向方式直接返回重寫后生成的新URI給客戶端淑蔚,由客戶端重新發(fā)起請求市殷,此重定向信息可緩存,狀態(tài)碼:301

    location /break {
    rewrite ^/break/(.*) /test/$1 break; #break不會(huì)跳轉(zhuǎn)到其他的location
      return 666 "break";
    }
    location /last {
      rewrite ^/last/(.*) /test/$1 last; #last會(huì)跳轉(zhuǎn)到其他的location繼續(xù)匹配新的URI
      return 888 "last";
    }
    location /test {
      return 999 "test";
      index index.html;
      root /data/nginx;
    }
    mkdir /data/nginx/test/
    echo test Page > /data/nginx/test/index.html
    
    #rewrite 生產(chǎn)案例
    #要求:將 http:// 請求跳轉(zhuǎn)到 https://
    #生產(chǎn)案例
    location / {
      if ($scheme = http ) {
          rewrite / https://www.magedu.net/ redirect;
      }
    }
    
    #要求:當(dāng)用戶訪問到公司網(wǎng)站的時(shí)輸入了一個(gè)錯(cuò)誤的URL刹衫,可以將用戶重定向至官網(wǎng)首頁
    #生產(chǎn)案例
    location / {
      root /data/nginx/html/pc;
      index index.html;
      if (!-f $request_filename) {
          #return 404 "No exsit";
          rewrite (.*) http://www.magedu.net/index.html;
      }
    }
    

    小筆記:http_rewrite模塊

    #重定向
    vim /etc/nginx/conf.d/test.conf
    server {
      listen 80;
      listen 443 ssl;
      server_name www.magedu.net;
      root /data/test;
      ssl_certificate /etc/nginx/ssl/magedu.net.crt;
      ssl_certificate_key /etc/nginx/ssl/magedu.net.key;
      ssl_session_cache shared:sslcache:20m;
      ssl_session_timeout 10m;
      access_log /var/log/nginx/magedu_net.ssl.access.log access_json;
      location / {
          if ( $scheme = http ){
              return 301 https://www.magedu.net/;
          }
      }
    }
    
    #禁止某瀏覽器訪問
    vim /etc/nginx/conf.d/test.conf
    server {
      listen 80;
      listen 443 ssl;
      server_name www.magedu.net;
      root /data/test;
      ssl_certificate /etc/nginx/ssl/magedu.net.crt;
      ssl_certificate_key /etc/nginx/ssl/magedu.net.key;
      ssl_session_cache shared:sslcache:20m;
      ssl_session_timeout 10m;
      access_log /var/log/nginx/magedu_net.ssl.access.log access_json;
      location / {
          if ( $scheme = http ){
              return 301 https://www.magedu.net/;
          }
          if ( $http_user_agent ~* curl ){        #判斷瀏覽器類型
              return 403;
          }
      }
    }
    
    #rewrite
    vim /etc/nginx/conf.d/test.conf
    server {
      location /test1 {
          rewrite ^/test1/(.*)$ /test2/$1 last;   #last|break|redirect|permanent
      }
      location /test2 {
          default_type text/html;
          echo test2;
      }
    }
    
    vim /etc/nginx/conf.d/test.conf
    server {
      listen 80;
      listen 443 ssl;
      server_name www.magedu.net;
      root /data/test;
      ssl_certificate /etc/nginx/ssl/magedu.net.crt;
      ssl_certificate_key /etc/nginx/ssl/magedu.net.key;
      ssl_session_cache shared:sslcache:20m;
      ssl_session_timeout 10m;
      access_log /var/log/nginx/magedu_net.ssl.access.log access_json;
      location / {
          if ( $scheme = http ){
              rewrite ^/(.*)$ https://www.magedu.net/$1 redirect;     #重定向https
          }
      }
    }
    
    #雙https
    cd /etc/pki/tls/certs
    vim Makefile
    %.key:
      umask 77; \
      #/usr/bin/openssl genrsa -aes128 $(KEYLEN) > $@
      /usr/bin/openssl genrsa $(KEYLEN) > $@                          #把加密去掉
    make magedu.org.crt
    CN
    beijing
    beijing
    magedu.org
    opt
    www.magedu.org
    mv magedu.or.* /etc/nginx/ssl
    mkdir /data/site{1,2}
    echo /data/site1/index.html > /data/site1/index.html
    echo /data/site2/index.html > /data/site2/index.html
    
    vim /etc/nginx/conf.d/test.conf
    server {
      listen 80;
      listen 443 ssl;
      server_name www.magedu.net;
      root /data/site1;
      ssl_certificate /etc/nginx/ssl/magedu.net.crt;
      ssl_certificate_key /etc/nginx/ssl/magedu.net.key;
      ssl_session_cache shared:sslcache:20m;
      ssl_session_timeout 10m;
      access_log /var/log/nginx/magedu_net.ssl.access.log access_json;
      location / {
          if ( $scheme = http ){
              rewrite ^/(.*)$ https://www.magedu.net/$1 redirect;     #重定向https
          }
          if ( !-f $request_filename ) {
              rewrite ^/(.*)$ http://www.magedu.net/index.html;       #錯(cuò)誤頁面重定向到主頁
          }
      }
    }
    server {
      listen 80;
      listen 443 ssl;
      server_name www.magedu.org;
      root /data/site2;
      ssl_certificate /etc/nginx/ssl/magedu.org.crt;
      ssl_certificate_key /etc/nginx/ssl/magedu.org.key;
      ssl_session_cache shared:sslcache:20m;
      ssl_session_timeout 10m;
      access_log /var/log/nginx/magedu_org.ssl.access.log access_json;
      location / {
          if ( $scheme = http ){
              rewrite ^/(.*)$ https://www.magedu.org/$1 redirect;     #重定向https
          }
            if ( !-f $request_filename ) {
              rewrite ^/(.*)$ http://www.magedu.org/index.html;       #錯(cuò)誤頁面重定向到主頁
          }
      }
    }
    

ngx_http_referer_module

  • ngx_http_referer_module模塊:
    用來阻止Referer首部無有效值的請求訪問醋寝,可防止盜鏈
  • valid_referers none|blocked|server_names|string ...;
    定義referer首部的合法可用值搞挣,不能匹配的將是非法值
    none:請求報(bào)文首部沒有referer首部
    blocked:請求報(bào)文有referer首部,但無有效值
    server_names:referer首部中包含本主機(jī)名
    arbitrary_string:任意字符串音羞,但可使用作通配符
    regular expression:被指定的正則表達(dá)式模式匹配到的字符串,要使用~開頭囱桨,
    例如: ~.
    .magedu.com
防止盜鏈生產(chǎn)案例:
valid_referers none block server_names
*.magedu.com magedu.* *.mageedu.com mageedu.* ~\.magedu\.
~\.google\. ~\.baidu\.;
if ($invalid_referer) {
    return 403 "Forbidden Access";
}  

小筆記:防盜鏈

cp sunflower.jpg /data/site2/sun.jpg
vim /data/site1/daolian.html
<img src=http://www.magedu.org/sun.jpg>

vim /etc/nginx/conf.d/test.conf
server {
    listen 80;
    listen 443 ssl;
    server_name www.magedu.net;
    root /data/site1;
    ssl_certificate /etc/nginx/ssl/magedu.net.crt;
    ssl_certificate_key /etc/nginx/ssl/magedu.net.key;
    ssl_session_cache shared:sslcache:20m;
    ssl_session_timeout 10m;
    access_log /var/log/nginx/magedu_net.ssl.access.log access_json;
    location / {
        if ( !-f $request_filename ) {
            rewrite ^/(.*)$ http://www.magedu.net/index.html;       #錯(cuò)誤頁面重定向到主頁
        }
    }
}
server {
    listen 80;
    listen 443 ssl;
    server_name www.magedu.org;
    root /data/site2;
    ssl_certificate /etc/nginx/ssl/magedu.org.crt;
    ssl_certificate_key /etc/nginx/ssl/magedu.org.key;
    ssl_session_cache shared:sslcache:20m;
    ssl_session_timeout 10m;
    access_log /var/log/nginx/magedu_org.ssl.access.log access_json;
    location / {
        if ( !-f $request_filename ) {
            rewrite ^/(.*)$ http://www.magedu.org/index.html;       #錯(cuò)誤頁面重定向到主頁
        }
    }
    valid_referers none block server_names *.magedu.com magedu.* *.mageedu.com mageedu.* ~\.magedu\. ~\.google\. ~\.baidu\.;    #除了定義的域名,其他不允許鏈接嗅绰,防盜鏈
    if ($invalid_referer) {
        return 403 "Forbidden Access";
    }  
}

nginx反向代理

image.png
  • 反向代理:reverse proxy舍肠,可代理外網(wǎng)用戶的請求到內(nèi)部的指定web服務(wù)器,并將數(shù)據(jù)返回給用戶
  • nginx除了可以在企業(yè)提供高性能的web服務(wù)之外窘面,另外還可以將本身不具備的請求通過某種預(yù)定義的協(xié)議轉(zhuǎn)發(fā)至其它服務(wù)器處理翠语,不同的協(xié)議就是nginx服務(wù)器與其他服務(wù)器進(jìn)行通信的一種規(guī)范
  • 主要在不同的場景使用以下模塊實(shí)現(xiàn)不同的功能:
    ngx_http_proxy_module: 將客戶端請求以http協(xié)議轉(zhuǎn)發(fā)至后端服務(wù)器
    ngx_http_fastcgi_module:將客戶端對php請求以fastcgi協(xié)議轉(zhuǎn)發(fā)至后端
    ngx_http_uwsgi_module:將客戶端對Python請求以uwsgi協(xié)議轉(zhuǎn)發(fā)至后端
    ngx_stream_proxy_module:將客戶端請求以tcp協(xié)議轉(zhuǎn)發(fā)至后端服務(wù)器

ngx_http_proxy_module

  • ngx_http_proxy_module模塊:
    轉(zhuǎn)發(fā)請求至另一臺主機(jī)
    proxy_pass URL;
    注意:proxy_pass后面路徑不帶uri時(shí),會(huì)將location的uri傳遞(附加)給后端主機(jī)

    server {
      ...
      server_name HOSTNAME;
      location /uri/ {
          proxy_pass http://host[:port]; 注意:最后沒有/
      }
      ...
    }
    

    上面示例:http://HOSTNAME/uri --> http://host/uri 财边,功能類似 root
    如果上面示例中有 /肌括,即:http://host[:port]/ 此方式較少使用
    意味著:http://HOSTNAME/uri --> http://host/ 即置換,功能類似 alias

  • proxy_pass后面的路徑是一個(gè)uri時(shí)酣难,其會(huì)將location的uri替換為proxy_pass的

    uri
    server {
      ...
      server_name HOSTNAME;
      location /uri/ {
          proxy_pass http://host/new_uri/;
      }
      ...
    }
    http://HOSTNAME/uri/ --> http://host/new_uri/  
    
  • 如果location定義其uri時(shí)使用了正則表達(dá)式的模式谍夭,則proxy_pass之后必須不能使用uri; 用戶請求時(shí)傳遞的uri將直接附加至后端服務(wù)器之后

    server {
      ...
      server_name HOSTNAME;
      location ~|~* /uri/ {
          proxy_pass http://host; 不能加/
      }
      ...
    }
    http://HOSTNAME/uri/ --> http://host/uri/
    
  • proxy_set_header field value;
    設(shè)定轉(zhuǎn)發(fā)往后端主機(jī)的請求報(bào)文的請求首部的值;
    Context: http, server, location
    proxy_set_header X-Real-IP remote_addr; proxy_set_header X-Forwarded-Forproxy_add_x_forwarded_for;

    • 請求報(bào)文的標(biāo)準(zhǔn)格式如下:
      X-Forwarded-For: client1, proxy1, proxy2
  • proxy_cache_path;

    ● 定義可用于proxy功能的緩存憨募;Context:http
    ● proxy_cache_path path [levels=levels] [use_temp_path=on|off]
    keys_zone=name:size [inactive=time] [max_size=size]
    [manager_files=number] [manager_sleep=time] [manager_threshold=time]
    [loader_files=number] [loader_sleep=time] [loader_threshold=time]
    [purger=on|off] [purger_files=number] [purger_sleep=time]
    [purger_threshold=time];
    示例:在http配置定義緩存信息

    proxy_cache_path /var/cache/nginx/proxy_cache #定義緩存保存路徑慧库,proxy_cache會(huì)自動(dòng)創(chuàng)建
    levels=1:2:2 #定義緩存目錄結(jié)構(gòu)層次,1:2:2 可以生成2^4x2^8x2^8=1048576個(gè)目錄
    keys_zone=proxycache:20m #指內(nèi)存中緩存的大小馋嗜,主要用于存放key和metadata(如:使用次數(shù))
    inactive=120s齐板; #緩存有效時(shí)間
    max_size=1g; #最大磁盤占用空間,磁盤存入文件內(nèi)容的緩存空間最大值
    

    ● proxy_cache zone | off; 默認(rèn)off
    指明調(diào)用的緩存葛菇,或關(guān)閉緩存機(jī)制甘磨;Context:http, server, location
    ● proxy_cache_key string;
    緩存中用于“鍵”的內(nèi)容
    默認(rèn)值:proxy_cache_key schemeproxy_host$request_uri;
    ● proxy_cache_valid [code ...] time;
    定義對特定響應(yīng)碼的響應(yīng)內(nèi)容的緩存時(shí)長
    定義在http{...}中
    示例:
    proxy_cache_valid 200 302 10m;
    proxy_cache_valid 404 1m;

    • 示例:在http配置定義緩存信息
    proxy_cache_path /var/cache/nginx/proxy_cache
    levels=1:2:2 keys_zone=proxycache:20m
    inactive=120s max_size=1g;
    #說明:proxycache:20m 指內(nèi)存中緩存的大小,主要用于存放key和metadata(如:使用次數(shù))
    max_size=1g #指磁盤存入文件內(nèi)容的緩存空間最大值
    #調(diào)用緩存功能眯停,需要定義在相應(yīng)的配置段济舆,如server{...};
    proxy_cache proxycache;
    proxy_cache_key $request_uri;
    proxy_cache_valid 200 302 301 1h;
    proxy_cache_valid any 1m;
    
  • proxy_cache_use_stale;
    proxy_cache_use_stale error | timeout | invalid_header | updating |
    http_500 | http_502 | http_503 | http_504 | http_403 | http_404 | off ...
    在被代理的后端服務(wù)器出現(xiàn)哪種情況下莺债,可直接使用過期的緩存響應(yīng)客戶端

  • proxy_cache_methods GET | HEAD | POST ...;
    對哪些客戶端請求方法對應(yīng)的響應(yīng)進(jìn)行緩存滋觉,GET和HEAD方法總是被緩存

  • proxy_hide_header field;
    用于隱藏后端服務(wù)器特定的響應(yīng)首部,默認(rèn)nginx在響應(yīng)報(bào)文中不傳遞后端服務(wù)器的首部字段Date, Server, X-Pad, X-Accel等
    示例:
    proxy_hide_header Etag;

  • proxy_pass_header field;
    默認(rèn)nginx在響應(yīng)報(bào)文中不傳遞后端服務(wù)器的首部字段Date, Server, X-Pad, X-Accel等參數(shù)齐邦,如果要傳遞的話則要使用 proxy_pass_header field聲明將后端服務(wù)器返回的值傳遞給客戶端

小筆記:http_proxy_module模塊

#調(diào)度(rs訪問日志看不到真正的訪問ip地址)
vim /etc/nginx/conf.d/test.conf
server {
    listen 80;
    server_name www.magedu.net;
    root /data/site1;
    access_log /var/log/nginx/magedu_net.ssl.access.log access_json;
    location ~* ^.*\.(jpg|gif|bmp|jpeg)$ {
        proxy_pass http://192.168.37.37;
    }
    location /api {
        proxy_pass http://192.168.37.47;
    }
}

#37
yum install httpd -y
echo 37 > /var/www/html/index.html
cp sky.jpg /var/www/html/
systemctl start httpd

#47
yum install httpd -y
mkdir /var/www/html/api
echo api > /var/www/html/api/index.html
systemctl start httpd

#----------------分割線--------------------#

#調(diào)度(rs訪問日志看到真正的訪問ip地址)
vim /etc/nginx/conf.d/test.conf
server {
    listen 80;
    server_name www.magedu.net;
    root /data/site1;
    access_log /var/log/nginx/magedu_net.ssl.access.log access_json;
    location ~* ^.*\.(jpg|gif|bmp|jpeg)$ {
        proxy_pass http://192.168.37.37;
    }
    location /api {
        #proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_pass http://192.168.37.47;
    }
}

#rs修改日志格式
vim /etc/httpd/conf/httpd.conf
LogFormat "\"%{X-Forwarded-For}i\" %h ..." nginxlog

#----------------分割線--------------------#

#啟用緩存
vim /etc/nginx/nginx.conf
http {
    proxy_cache_path /var/cache/nginx/proxy_cache levels=1:2:2 keys_zone=proxycache:20m inactive=120s max_size=1g;  
    ...
}
vim /etc/nginx/conf.d/test.conf
server {
    listen 80;
    server_name www.magedu.net;
    root /data/site1;
    access_log /var/log/nginx/magedu_net.ssl.access.log access_json;
    #調(diào)用緩存
    proxy_cache proxycache;
    proxy_cache_key $request_uri;
    proxy_cache_valid 200 302 301 1h;
    proxy_cache_valid any 1m;
    proxy_hide_header Etag;             #隱藏ETAG
    #proxy_pass_header Server;              #后端軟件版本號替換為前端版本號
    location ~* ^.*\.(jpg|gif|bmp|jpeg)$ {
        proxy_pass http://192.168.37.37;
    }
    location /api {
        #proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_pass http://192.168.37.47;
    }
}
mkdir /var/cache/nginx/

ngx_http_headers_module

  • ngx_http_headers_module模塊
    向代理服務(wù)器給客戶端的響應(yīng)報(bào)文添加自定義首部椎侠,或修改指定首部的值
  • add_header name value [always];
    添加自定義首部
    add_header X-Via server_addr; add_header X-Cacheupstream_cache_status;
    add_header X-Accel $server_name;
  • add_trailer name value [always];
    添加自定義響應(yīng)信息的尾部, 1.13.2版后支持
  • proxy_connect_timeout time;
    定義與后端服務(wù)器建立連接的超時(shí)時(shí)長措拇,如超時(shí)會(huì)出現(xiàn)502錯(cuò)誤我纪,默認(rèn)為60s,
    一般不建議超出75s
  • proxy_send_timeout time;
    對后端服務(wù)器send,將請求發(fā)送給后端服務(wù)器的超時(shí)時(shí)長浅悉;默認(rèn)為60s
  • proxy_read_timeout time;
    從后端服務(wù)器read趟据,等待后端服務(wù)器發(fā)送響應(yīng)報(bào)文的超時(shí)時(shí)長,默認(rèn)為60s
  • proxy_ignore_client_abort off术健;
    當(dāng)客戶端網(wǎng)絡(luò)中斷請求時(shí)汹碱,nginx服務(wù)器中斷其對后端服務(wù)器的請求。即如果此項(xiàng)設(shè)置為on開啟荞估,則服務(wù)器會(huì)忽略客戶端中斷并一直等著代理服務(wù)執(zhí)行返回咳促,如果設(shè)置為off,則客戶端中斷后nginx也會(huì)中斷客戶端請求并立即記錄499日志泼舱,默認(rèn)為off
  • proxy_http_version 1.0等缀;
    用于設(shè)置nginx提供代理服務(wù)的HTTP協(xié)議的版本,默認(rèn)http 1.0
  • proxy_headers_hash_bucket_size 128娇昙;
    當(dāng)配置了 proxy_hide_header和proxy_set_header的時(shí)候尺迂,用于設(shè)置nginx保
    存HTTP報(bào)文頭的hash表的上限
  • proxy_headers_hash_max_size 512;
    設(shè)置proxy_headers_hash_bucket_size的最大可用空間
  • server_namse_hash_bucket_size 512;
    server_name hash表申請空間大小
  • server_names_hash_max_size 512;
    設(shè)置服務(wù)器名稱hash表的上限大小

小筆記:http_headers_module

vim /etc/nginx/conf.d/test.conf
server {
    listen 80;
    server_name www.magedu.net;
    root /data/site1;
    access_log /var/log/nginx/magedu_net.ssl.access.log access_json;
    #調(diào)用緩存
    proxy_cache proxycache;
    proxy_cache_key $request_uri;
    proxy_cache_valid 200 302 301 1h;
    proxy_cache_valid any 1m;
    proxy_hide_header Etag                  #隱藏ETAG
    proxy_pass_header Server                #后端軟件版本號替換為前端版本號
    add_header X-Cache $upstream_cache_status;  #添加響應(yīng)字段
    location ~* ^.*\.(jpg|gif|bmp|jpeg)$ {
        proxy_pass http://192.168.37.37;
    }
    location /api {
        #proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_pass http://192.168.37.47;
    }
}

ngx_http_fastcgi_module

  • ngx_http_fastcgi_module模塊
    轉(zhuǎn)發(fā)請求到FastCGI服務(wù)器冒掌,不支持php模塊方式

  • fastcgi_pass address;
    address為后端的fastcgi server的地址
    可用位置:location, if in location

  • fastcgi_index name;
    fastcgi默認(rèn)的主頁資源
    示例:fastcgi_index index.php;

  • fastcgi_param parameter value [if_not_empty];
    設(shè)置傳遞給 FastCGI 服務(wù)器的參數(shù)值噪裕,可以是文本,變量或組合

  • 示例1:
    1)在后端服務(wù)器先配置fpm server和mariadb-server
    2)在前端nginx服務(wù)上做以下配置:

    location ~* \.php$ {
      root /data/php; #$document_root 調(diào)用root目錄
      fastcgi_pass 后端fpm服務(wù)器IP:9000;
      fastcgi_index index.php;
      fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
      #fastcgi_param SCRIPT_FILENAME /data/php$fastcgi_script_name;
      #如果SCRIPT_FILENAME是絕對路徑,則可以省略root /data/php;
      include fastcgi_params;
    }
    
  • 示例2:通過/pm_status和/ping來獲取fpm server狀態(tài)信息

    location ~* ^/(fpm_status|ping)$ {
      fastcgi_pass 后端fpm服務(wù)器IP:9000;
      fastcgi_param SCRIPT_FILENAME $fastcgi_script_name;
      include fastcgi_params;
    }
    
    cat /etc/php-fpm.d/www.conf
    [www]
    listen = 127.0.0.1:9000 #監(jiān)聽地址及IP
    listen.allowed_clients = 127.0.0.1 #允許客戶端從哪個(gè)源IP地址訪問股毫,要允許所有行首加 ;注釋即可
    user = nginx #php-fpm啟動(dòng)的用戶和組膳音,會(huì)涉及到后期文件的權(quán)限問題
    group = nginx
    pm = dynamic #動(dòng)態(tài)模式進(jìn)程管理
    pm.max_children = 500 #靜態(tài)方式下開啟的php-fpm進(jìn)程數(shù)量,在動(dòng)態(tài)方式下他限定php-fpm的最大進(jìn)程數(shù)
    pm.start_servers = 100 #動(dòng)態(tài)模式下初始進(jìn)程數(shù)铃诬,必須大于等于pm.min_spare_servers和小于等于pm.max_children的值祭陷。
    pm.min_spare_servers = 100 #最小空閑進(jìn)程數(shù)
    pm.max_spare_servers = 200 #最大空閑進(jìn)程數(shù)
    pm.max_requests = 500000 #進(jìn)程累計(jì)請求回收值,會(huì)重啟
    pm.status_path = /pm_status #狀態(tài)訪問URL
    ping.path = /ping #ping訪問動(dòng)地址
    ping.response = ping-pong #ping返回值
    slowlog = /var/log/php-fpm/www-slow.log #慢日志路徑
    php_admin_value[error_log] = /var/log/php-fpm/www-error.log #錯(cuò)誤日志
    php_admin_flag[log_errors] = on
    php_value[session.save_handler] = files #phpsession保存方式及路徑
    php_value[session.save_path] = /var/lib/php/session #當(dāng)時(shí)使用file保存session的文件路徑
    
  • fastcgi_cache_path path [levels=levels] [use_temp_path=on|off] keys_zone=name:size
    [inactive=time] [max_size=size] [manager_files=number] [manager_sleep=time]
    [manager_threshold=time] [loader_files=number] [loader_sleep=time]
    [loader_threshold=time] [purger=on|off] [purger_files=number] [purger_sleep=time]
    [purger_threshold=time];

  • 定義fastcgi的緩存趣席;
    path 緩存位置為磁盤上的文件系統(tǒng)路徑
    max_size=size
    磁盤path路徑中用于緩存數(shù)據(jù)的緩存空間上限
    levels=levels:緩存目錄的層級數(shù)量兵志,以及每一級的目錄數(shù)量,levels=ONE:TWO:THREE
    示例:leves=1:2:2
    keys_zone=name:size
    k/v映射的內(nèi)存空間的名稱及大小
    inactive=time
    非活動(dòng)時(shí)長

  • fastcgi_cache zone | off;
    調(diào)用指定的緩存空間來緩存數(shù)據(jù)宣肚,可用位置:http, server, location

  • fastcgi_cache_key string;
    定義用作緩存項(xiàng)的key的字符串
    示例:fastcgi_cache_key $request_uri;

  • fastcgi_cache_methods GET | HEAD | POST ...;
    為哪些請求方法使用緩存

  • fastcgi_cache_min_uses number;
    緩存項(xiàng)在inactive定義的非活動(dòng)時(shí)間內(nèi)至少要被訪問到指定的次數(shù)方可被認(rèn)作活動(dòng)項(xiàng)

  • fastcgi_keep_conn on | off;
    收到后端服務(wù)器響應(yīng)后想罕,fastcgi服務(wù)器是否關(guān)閉連接,建議啟用長連接

  • fastcgi_cache_valid [code ...] time;
    不同的響應(yīng)碼各自的緩存時(shí)長

    示例:

    http {
      fastcgi_cache_path /var/cache/nginx/fcgi_cache levels=1:2:1 keys_zone=fcgicache:20m inactive=120s;
      ...
      server {
          location ~* \.php$ {
              ...
              fastcgi_cache fcgicache;
              fastcgi_cache_key $request_uri;
              fastcgi_cache_valid 200 302 10m;
              fastcgi_cache_valid 301 1h;
              fastcgi_cache_valid any 1m;
              ...
          }
      }
    }    
    

小筆記:搭建fastcgi

#server
yum install php-fpm php-mysql
vim /etc/php-fpm.d/www.conf
    user = nginx
    group = nginx
    pm.status_path = /fpm_status
    ping.path = /ping
systemctl start php-fpm
mkdir /data/php/

vim /etc/nginx/conf.d/test.conf
server {
    listen 80;
    server_name www.magedu.net;
    root /data/site1;
        index index.php;
    access_log /var/log/nginx/magedu_net.ssl.access.log access_json;
    location ~* \.php$ {
        root /data/php;
        fastcgi_pass 127.0.0.1:9000;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
    }
    location ~* ^/(fpm_status|ping)$ {
        fastcgi_pass 127.0.0.1:9000;
        fastcgi_param SCRIPT_FILENAME $fastcgi_script_name;
        include fastcgi_params;
    }
}
tar xf wordpress-5.1.1-zh_CN.tar.gz -C /data/php
cd /data/php/wordpress
cp -a wp-config-sample.php  wp-config.php
vim wp-config.php
define( 'DB_NAME', 'wordpress' );
define( 'DB_USER', 'wordpress' );
define( 'DB_PASSWORD', 'centos' );
define( 'DB_HOST', '192.168.37.27' );
cp -a * /data/site1
mkdir /data/php/wp-content/uploads
setfacl -R -m u:nginx:rwx /data/php
setfacl -R -m u:nginx:rwx /data/site1
systemctl restart nginx php-fpm

#mysql-server
yum install mariadb
systemctl start mariadb
mysql -e 'create database wordpress;grant all on wordpress.* to wordpress@"192.168.37.%" identified by "centos"'
mysql -e 'flush privileges;'

#client
http://www.magedu.net/wordpress
http://www.magedu.net/fpm_status
http://www.magedu.net/fpm_status?full
http://www.magedu.net/fpm_status?xml
http://www.magedu.net/fpm_status?json

小筆記:安裝新版本php

#server
yum install https://mirror.tuna.tsinghua.edu.cn/remi/enterprise/remi-release-7.rpm
vim /etc/yum.repos.d/remi-php73.repo
[remi-php73]
enabled=1
yum install php73-php-fpm php73-php-mysql
groupadd -g 981 nginx
useradd -u -r 987 -g nginx -s /sbin/nologin nginx
vim /etc/php73-php-fpm.d/www.conf
    user = nginx
    group = nginx
    listen = 9000
    ;listen.allowed_clients = 127.0.0.1     #注釋掉
    pm.status_path = /fpm_status
    ping.path = /ping
    
vim /etc/nginx/conf.d/test.conf
server {
    listen 80;
    server_name www.magedu.net;
    root /data/php;
    access_log /var/log/nginx/magedu_net.ssl.access.log access_json;
    location ~* \.php$ {
        fastcgi_pass 127.0.0.1:9000;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME /data/php$fastcgi_script_name;
        include fastcgi_params;
    }
    location ~* ^/(fpm_status|ping)$ {
        fastcgi_pass 127.0.0.1:9000;
        fastcgi_param SCRIPT_FILENAME $fastcgi_script_name;
        include fastcgi_params;
    }
}
tar xf wordpress-5.1.1-zh_CN.tar.gz -C /data/php
cd /data/php/wordpress
cp -a wp-config-sample.php  wp-config.php
vim wp-config.php
define( 'DB_NAME', 'wordpress' );
define( 'DB_USER', 'wordpress' );
define( 'DB_PASSWORD', 'centos' );
define( 'DB_HOST', '192.168.37.27' );
systemctl restart php73-php-fpm nginx

小筆記:nginx開啟php-fpm緩存

#server
vim /etc/nginx/nginx.conf
http {
    fastcgi_cache_path /var/cache/nginx/fcgi_cache levels=1:2:1 keys_zone=fcgicache:20m inactive=120s;
    ...
}
vim /etc/nginx/conf.d/test.conf
server {
    listen 80;
    server_name www.magedu.net;
    root /data/site1;
    access_log /var/log/nginx/magedu_net.ssl.access.log access_json;
    location ~* \.php$ {
        fastcgi_pass 127.0.0.1:9000;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME /data/php$fastcgi_script_name;
        include fastcgi_params;
    }
    location ~* ^/(fpm_status|ping)$ {
        fastcgi_pass 127.0.0.1:9000;
        fastcgi_param SCRIPT_FILENAME $fastcgi_script_name;
        include fastcgi_params;
    }
    #開啟fastcgi緩存
    fastcgi_cache fcgicache;
    fastcgi_cache_key $request_uri;
    fastcgi_cache_valid 200 302 10m;
    fastcgi_cache_valid 301 1h;
    fastcgi_cache_valid any 1m;
}

ngx_http_upstream_module (高可用調(diào)度)

  • ngx_http_upstream_module模塊
    將多個(gè)服務(wù)器定義成服務(wù)器組霉涨,而由proxy_pass, fastcgi_pass等指令進(jìn)行引用

  • upstream name { ... }
    定義后端服務(wù)器組按价,會(huì)引入一個(gè)新的上下文
    默認(rèn)調(diào)度算法是wrr

    Context: http
    upstream httpdsrvs {
      server ...
      server...
      ...
    } 
    
  • server address [parameters];
    在upstream上下文中server成員,以及相關(guān)的參數(shù)笙瑟;Context:upstream

    address的表示格式:
      unix:/PATH/TO/SOME_SOCK_FILE
      IP[:PORT]
      HOSTNAME[:PORT]
    parameters:
      weight=number 權(quán)重楼镐,默認(rèn)為1
      max_conns 連接后端報(bào)務(wù)器最大并發(fā)活動(dòng)連接數(shù),1.11.5后支持
      max_fails=number 失敗嘗試最大次數(shù)逮走;超出此處指定的次數(shù)時(shí)鸠蚪,server將被標(biāo)
      記為不可用,默認(rèn)為1
      fail_timeout=time 后端服務(wù)器標(biāo)記為不可用狀態(tài)的連接超時(shí)時(shí)長今阳,默認(rèn)10s
      backup 將服務(wù)器標(biāo)記為“備用”师溅,即所有服務(wù)器均不可用時(shí)才啟用
      down 標(biāo)記為“不可用”茅信,實(shí)現(xiàn)灰度發(fā)布
    
  • nginx調(diào)度算法:

    • ip_hash 源地址hash調(diào)度方法

    • least_conn 最少連接調(diào)度算法,當(dāng)server擁有不同的權(quán)重時(shí)其為wlc墓臭,當(dāng)所有后端主機(jī)連接數(shù)相同時(shí)蘸鲸,則使用wrr,適用于長連接

    • hash key [consistent] 基于指定的key的hash表來實(shí)現(xiàn)對請求的調(diào)度窿锉,此處的key可以直接文本酌摇、變量或二者組合
      作用:將請求分類,同一類請求將發(fā)往同一個(gè)upstream server嗡载,使用consistent參數(shù)窑多,將使用ketama一致性hash算法,適用于后端是Cache服務(wù)器(如varnish)時(shí)使用
      hash request_uri consistent; #目標(biāo)地址hash洼滚,相當(dāng)于lvs的DH調(diào)度算法 hashremote_addr; #跟ip_hash一樣
      hash $cookie_name; #key為name的cookie

    • keepalive 連接數(shù)N;
      為每個(gè)worker進(jìn)程保留的空閑的長連接數(shù)量埂息,可節(jié)約nginx端口,并減少連接管理的消耗

小筆記:nginx高可用調(diào)度

#server
vim /etc/nginx/nginx.conf
http {
    upstream websrvs {              #默認(rèn)調(diào)度wrr
        server 192.168.37.37:80;
        server 192.168.37.47:80;
        server 192.168.37.37:80 weight=3;   #權(quán)重
        server 192.168.37.47:80;
        #server 192.168.37.47:80 down;      #下線
        server 127.0.0.1:8080 backup;
    }
}
vim /etc/nginx/conf.d/test.conf
server {
    listen 80;
    server_name www.magedu.net;
    root /data/site1;
    index index.html
    access_log /var/log/nginx/magedu_net.ssl.access.log access_json;
    location / {
        proxy_pass http://websrvs;          #多組服務(wù)器方向代理
    }
    location ~* \.php$ {
        fastcgi_pass 127.0.0.1:9000;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME /data/php$fastcgi_script_name;
        include fastcgi_params;
    }
    #開啟fastcgi緩存
    fastcgi_cache fcgicache;
    fastcgi_cache_key $request_uri;
    fastcgi_cache_valid 200 302 10m;
    fastcgi_cache_valid 301 1h;
    fastcgi_cache_valid any 1m;
}
server {
    listen 8080;
    root /data/site2;
    index index.html
    access_log /var/log/nginx/magedu_net.sorry.access.log access_json;
}

#rs
systemctl stop httpd

#----------------分割線---------------------#

#調(diào)度算法
vim /etc/nginx/nginx.conf
http {
    upstream websrvs {              #默認(rèn)調(diào)度wrr
        server 192.168.37.37:80;
        server 192.168.37.47:80;
        server 192.168.37.37:80 weight=3;   #權(quán)重
        server 192.168.37.47:80;
        #server 192.168.37.47:80 down;      #下線
        server 127.0.0.1:8080;
        hash $cookie_sessionid;             #調(diào)度算法
    }
    location /echo {
        default_type text/html;
        echo hello;
        echo $cookie_sessionid;
    }
}

vim setcookie.php
<?php
setcookie('title','cto');
setcookie('sessionid','123456');
setcookie('user','wang',time()+3600*12);
?>

#說明:此調(diào)度方法缺點(diǎn):down機(jī)后會(huì)使后端服務(wù)器壓力過大

#client
curl -b sessionid=123456 192.168.37.7/echo      #指定cookie

一致性hash算法

解決了上面調(diào)度算法的缺點(diǎn)

http {
    hash $cookie_sessionid consistent;
}

ngx_stream_core_module

  • ngx_stream_core_module模塊
    模擬反代基于tcp或udp的服務(wù)連接遥巴,即工作于傳輸層的反代或調(diào)度器

  • stream { ... }
    定義stream相關(guān)的服務(wù)千康;Context:main

    stream {
      upstream mysqlsrvs {
          server 192.168.8.2:3306;
          server 192.168.8.3:3306;
          least_conn;
      }
      server {
          listen 10.1.0.6:3306;
          proxy_pass mysqlsrvs;
      }
    }  
    
  • listen

    listen address:port [ssl] [udp] [proxy_protocol] [backlog=number] [bind]
      [ipv6only=on|off] [reuseport] [so_keepalive=on|off|[keepidle]:[keepintvl]:[keepcnt]]; 
    

ngx_stream_proxy_module

  • ngx_stream_proxy_module模塊
    可實(shí)現(xiàn)代理基于TCP,UDP (1.9.13), UNIX-domain sockets的數(shù)據(jù)流

  • proxy_pass address;
    指定后端服務(wù)器地址

  • proxy_timeout timeout;
    無數(shù)據(jù)傳輸時(shí)铲掐,保持連接狀態(tài)的超時(shí)時(shí)長
    默認(rèn)為10m

  • proxy_connect_timeout time;
    設(shè)置nginx與被代理的服務(wù)器嘗試建立連接的超時(shí)時(shí)長
    默認(rèn)為60s

TCP反向代理生產(chǎn)案例

stream {
    upstream mysql_servers {
        server 192.168.0.10:3306;
        server 192.168.0.11:3306;
        hash $remote_addr consistent;
    }
    server {
        listen 172.16.100.100:3306;
        proxy_pass mysql_servers;
        proxy_timeout 60s;
        proxy_connect_timeout 10s;
    }
}

stream {
    upstream redis_servers {
        server 192.168.0.10:6379 max_fails=3 fail_timeout=30s;
    }
    server {
        listen 172.16.100.100:6379;
        proxy_pass redis_servers;
        proxy_timeout 60s;
        proxy_connect_timeout 10s;
    }
}

小筆記:基于傳輸層(tcp/udp)的反向代理調(diào)度

#mysql-server1
yum install mariadb -y
systemctl start mariadb
mysql -e "create database db37;grant all on *.* to test@'192.168.37.%' identified by 'centos';flush privileges"

#mysql -server2
yum install mariadb -y
systemctl start mariadb
mysql -e "create database db47;grant all on *.* to test@'192.168.37.%' identified by 'centos';flush privileges"

#nginx-server
vim /etc/nginx/nginx.conf
stream {
    upstream mysqlsrvs {
        server 192.168.37.37:3306;
        server 192.168.37.47:3306;
        least_conn;
    }
    server {
        listen 192.168.37.7:3306;
        proxy_pass mysqlsrvs;
    }
}

#client
mysql -utest -pcentos -h192.168.37.7 -e "show databases"

Tengine

  • Tengine是由淘寶網(wǎng)發(fā)起的Web服務(wù)器項(xiàng)目拾弃。它在Nginx的基礎(chǔ)上,針對大訪問量網(wǎng)站的需求摆霉,添加了很多高級功能和特性豪椿。 Tengine的性能和穩(wěn)定性已經(jīng)在大型的網(wǎng)站如淘寶網(wǎng),天貓商城等得到了很好的檢驗(yàn)携栋。它的最終目標(biāo)是打造一個(gè)高效搭盾、穩(wěn)定、安全刻两、易用的Web平臺增蹭。
  • 官網(wǎng):
    http://tengine.taobao.org
  • 官方文檔:
    http://tengine.taobao.org/documentation_cn.html

Tengine特性

  • 繼承Nginx-1.16.0的所有特性,兼容nginx的配置
  • 支持HTTP的CONNECT方法磅摹,可用于正向代理場景
  • 支持異步OpenSSL滋迈,可使用硬件如:QAT進(jìn)行HTTPS的加速與卸載
  • 增強(qiáng)相關(guān)運(yùn)維、監(jiān)控能力,比如異步打印日志及回滾,本地DNS緩存,內(nèi)存監(jiān)控等
  • Stream模塊支持server_name指令
  • 更加強(qiáng)大的負(fù)載均衡能力户誓,包括一致性hash模塊饼灿、會(huì)話保持模塊,還可以對后端的服務(wù)器進(jìn)行主動(dòng)健康檢查帝美,根據(jù)服務(wù)器狀態(tài)自動(dòng)上線下線碍彭,以及動(dòng)態(tài)解析upstream中出現(xiàn)的域名
  • 輸入過濾器機(jī)制支持。通過使用這種機(jī)制Web應(yīng)用防火墻的編寫更為方便
  • 支持設(shè)置proxy、 memcached庇忌、 fastcgi舞箍、 scgi、 uwsgi在后端失敗時(shí)的重試次數(shù)
  • 動(dòng)態(tài)腳本語言Lua支持皆疹。擴(kuò)展功能非常高效簡單
  • 支持按指定關(guān)鍵字(域名疏橄,url等)收集Tengine運(yùn)行狀態(tài)
  • 組合多個(gè)CSS、 JavaScript文件的訪問請求變成一個(gè)請求
  • 自動(dòng)去除空白字符和注釋從而減小頁面的體積
  • 自動(dòng)根據(jù)CPU數(shù)目設(shè)置進(jìn)程個(gè)數(shù)和綁定CPU親緣性略就;
  • 監(jiān)控系統(tǒng)的負(fù)載和資源占用從而對系統(tǒng)進(jìn)行保護(hù)
  • 顯示對運(yùn)維人員更友好的出錯(cuò)信息捎迫,便于定位出錯(cuò)機(jī)器
  • 更強(qiáng)大的防攻擊(訪問速度限制)模塊
  • 更方便的命令行參數(shù),如列出編譯的模塊列表表牢、支持的指令等
  • 可以根據(jù)訪問文件類型設(shè)置過期時(shí)間

小筆記:源碼編譯tengine

yum install gcc pcre-devel openssl-devel zlib-devel
wget http://tengine.taobao.org/download/tengine-2.1.2.tar.gz        #此版本不支持傳輸層反向代理
tar -xf tengine-2.1.2.tar.gz
useradd -r -s /sbin/nologin nginx
cd tengine-2.1.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-http_concat_module       #tengine特有模塊,合并多個(gè)請求窄绒,一次性返回,提高訪問速度
make && make install

cd /apps/nginx/
vim conf/nginx.conf
    server {
        ...
        location / {
            ...
            concat on;
        }
        ...
    }
nginx -t
nginx

#模塊化編譯
./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-http_concat_module=shared        
make dso_install
make && make install
ls /apps/nginx/modules/
#加載模塊
vim /apps/nginx/conf/nginx.conf
dso {
    load ngx_http_concat_module.so;
}

實(shí)現(xiàn)nginx高并發(fā)Linux內(nèi)核優(yōu)化

  • 默認(rèn)的Linux內(nèi)核參數(shù)考慮的是最通用場景,不符合用于支持高并發(fā)訪問的Web服務(wù)器的定義崔兴,根據(jù)業(yè)務(wù)特點(diǎn)來進(jìn)行調(diào)整彰导,當(dāng)Nginx作為靜態(tài)web內(nèi)容服務(wù)器、反向代理或者提供壓縮服務(wù)器的服務(wù)器時(shí)恼布,內(nèi)核參數(shù)的調(diào)整都是不同的螺戳,此處針對最通用的、使Nginx支持更多并發(fā)請求的TCP網(wǎng)絡(luò)參數(shù)做簡單的配置,修改/etc/sysctl.conf來更改內(nèi)核參數(shù)

  • fs.file-max = 999999
    表示單個(gè)進(jìn)程較大可以打開的句柄數(shù)

  • net.ipv4.tcp_tw_reuse = 1
    參數(shù)設(shè)置為 1 折汞,表示允許將TIME_WAIT狀態(tài)的socket重新用于新的TCP鏈接倔幼,這對于服務(wù)器來說意義重大,因?yàn)榭傆写罅縏IME_WAIT狀態(tài)的鏈接存在

  • net.ipv4.tcp_keepalive_time = 600
    當(dāng)keepalive啟動(dòng)時(shí)爽待,TCP發(fā)送keepalive消息的頻度损同;默認(rèn)是2小時(shí),將其設(shè)置為10分鐘鸟款,可更快的清理無效鏈接

  • net.ipv4.tcp_fin_timeout = 30
    當(dāng)服務(wù)器主動(dòng)關(guān)閉鏈接時(shí)膏燃,socket保持在FIN_WAIT_2狀態(tài)的較大時(shí)間

  • net.ipv4.tcp_max_tw_buckets = 5000
    表示操作系統(tǒng)允許TIME_WAIT套接字?jǐn)?shù)量的較大值,如超過此值何什,TIME_WAIT套接字將立刻被清除并打印警告信息,默認(rèn)為8000组哩,過多的TIME_WAIT套接字會(huì)使Web服務(wù)器變慢

  • net.ipv4.ip_local_port_range = 1024 65000
    定義UDP和TCP鏈接的本地端口的取值范圍

  • net.ipv4.tcp_rmem = 10240 87380 12582912
    定義了TCP接受緩存的最小值、默認(rèn)值处渣、較大值

  • net.ipv4.tcp_wmem = 10240 87380 12582912
    定義TCP發(fā)送緩存的最小值伶贰、默認(rèn)值、較大值

  • net.core.netdev_max_backlog = 8096
    當(dāng)網(wǎng)卡接收數(shù)據(jù)包的速度大于內(nèi)核處理速度時(shí)罐栈,會(huì)有一個(gè)列隊(duì)保存這些數(shù)據(jù)包黍衙。這個(gè)參數(shù)表示該列隊(duì)的較大值

  • net.core.rmem_default = 6291456
    表示內(nèi)核套接字接受緩存區(qū)默認(rèn)大小

  • net.core.wmem_default = 6291456
    表示內(nèi)核套接字發(fā)送緩存區(qū)默認(rèn)大小

  • net.core.rmem_max = 12582912
    表示內(nèi)核套接字接受緩存區(qū)較大大小

  • net.core.wmem_max = 12582912
    表示內(nèi)核套接字發(fā)送緩存區(qū)較大大小

  • 注意:以上的四個(gè)參數(shù),需要根據(jù)業(yè)務(wù)邏輯和實(shí)際的硬件成本來綜合考慮

  • net.ipv4.tcp_syncookies = 1
    與性能無關(guān)荠诬。用于解決TCP的SYN攻擊

  • net.ipv4.tcp_max_syn_backlog = 8192
    這個(gè)參數(shù)表示TCP三次握手建立階段接受SYN請求列隊(duì)的較大長度琅翻,默認(rèn)1024位仁,將其設(shè)置的大一些可使出現(xiàn)Nginx繁忙來不及accept新連接時(shí),Linux不至于丟失客戶端發(fā)起的鏈接請求

  • net.ipv4.tcp_tw_recycle = 1
    這個(gè)參數(shù)用于設(shè)置啟用timewait快速回收

  • net.core.somaxconn=262114
    選項(xiàng)默認(rèn)值是128方椎,這個(gè)參數(shù)用于調(diào)節(jié)系統(tǒng)同時(shí)發(fā)起的TCP連接數(shù)聂抢,在高并發(fā)的請求中,默認(rèn)的值可能會(huì)導(dǎo)致鏈接超時(shí)或者重傳辩尊,因此需要結(jié)合高并發(fā)請求數(shù)來調(diào)節(jié)此值涛浙。

  • net.ipv4.tcp_max_orphans=262114
    選項(xiàng)用于設(shè)定系統(tǒng)中最多有多少個(gè)TCP套接字不被關(guān)聯(lián)到任何一個(gè)用戶文件句柄上康辑。如果超過這個(gè)數(shù)字摄欲,孤立鏈接將立即被復(fù)位并輸出警告信息。這個(gè)限制指示為了防止簡單的DOS攻擊疮薇,不用過分依靠這個(gè)限制甚至認(rèn)為的減小這個(gè)值胸墙,更多的情況是增加這個(gè)值

小筆記:keepalived+nginx實(shí)現(xiàn)高可用反向代理

#ka1:192.168.37.7,192.168.37.100、ka2:192.168.37.17,192.168.37.100按咒、rs1:192.168.37.37迟隅、rs2:192.168.37.47

#ka1
yum install keepalived nginx -y
vim /etc/keepalived/keepalived.conf
global_defs {
   notification_email {
     admin@magedu.net       #發(fā)給本機(jī)root郵件
   }
   notification_email_from ka1@magedu.net
   smtp_server 127.0.0.1    #發(fā)郵件的地址
   smtp_connect_timeout 30
   router_id ka1        #主機(jī)名    
   vrrp_mcast_group4 224.0.0.100    #D類地址,多播
}
vrrp_script chk_down {      #自定義腳本
    #script "[ -f /etc/keepalived/down ] && exit 1 || exit 0"
    script "/etc/keepalived/chk_down.sh"
    interval 1
    weight -30
}
vrrp_script chk_nginx {
    script "/etc/keepalived/chk_nginx.sh"
    interval 1
    weight -30
}
vrrp_instance VI_1 {    #虛擬路由器
    state MASTER        #在另一個(gè)結(jié)點(diǎn)上為BACKUP
    interface eth0      #網(wǎng)卡接口
    virtual_router_id 10    #多個(gè)節(jié)點(diǎn)必須相同
    priority 100        #優(yōu)先級励七,在另一個(gè)結(jié)點(diǎn)上要小于這個(gè)值
    advert_int 1        #通告間隔1s
    authentication {
        auth_type PASS  #預(yù)共享密鑰認(rèn)證
        auth_pass 123456    #密碼
    }
    virtual_ipaddress {
        192.168.37.100/24 dev eth0 label eth0:1
    }
    track_script {      #引用腳本
        chk_down
        chk_nginx
    }
    notify_master "/etc/keepalived/notify.sh master"
    notify_backup "/etc/keepalived/notify.sh backup"
    notify_fault "/etc/keepalived/notify.sh fault"
}

vim /etc/keepalived/notify.sh
#!/bin/bash
contact='root@localhost'
notify() {
    mailsubject="$(hostname) to be $1, vip floating"
    mailbody="$(date +'%F %T'): vrrp transition, $(hostname) changed to be $1"
    echo "$mailbody" | mail -s "$mailsubject" $contact
}
case $1 in
master)
    notify master
    ;;
backup)
    notify backup
    systemctl restart nginx
    ;;
fault)
    notify fault
    ;;
*)
    echo "Usage: $(basename $0) {master|backup|fault}"
    exit 1
    ;;
esac

vim /etc/nginx/nginx.conf
http {
    upstream websrvs {
        server 192.168.37.37:80;
        server 192.168.37.47:80;
        least_conn;
    }
    server {
        listen 80;
        location / {
            proxy_pass websrvs;
        }          
    }   
}
echo '[ -f /etc/keepalived/down ] && exit 1 || exit 0' > /etc/keepalived/chk_down.sh
echo 'killall -0 nginx &> /dev/null && exit 0 || exit 1' > /etc/keepalived/chk_nginx.sh
chmod +x  "/etc/keepalived/*.sh"
systemctl start keepalived nginx

#ka2
yum install keepalived nginx -y
vim /etc/keepalived/keepalived.conf
global_defs {
   notification_email {
     admin@magedu.net       #發(fā)給本機(jī)root郵件
   }
   notification_email_from ka2@magedu.net
   smtp_server 127.0.0.1    #發(fā)郵件的地址
   smtp_connect_timeout 30
   router_id ka2        #主機(jī)名    
   vrrp_mcast_group4 224.0.0.100    #D類地址智袭,多播
}
vrrp_script chk_down {      #自定義腳本
    #script "[ -f /etc/keepalived/down ] && exit 1 || exit 0"
    script "/etc/keepalived/chk_down.sh"
    interval 1
    weight -30
}
vrrp_script chk_nginx {
    script "/etc/keepalived/chk_nginx.sh"
    interval 1
    weight -30
}
vrrp_instance VI_1 {    #虛擬路由器
    state BACKUP        #在另一個(gè)結(jié)點(diǎn)上為BACKUP
    interface eth0      #網(wǎng)卡接口
    virtual_router_id 10    #多個(gè)節(jié)點(diǎn)必須相同
    priority 80     #優(yōu)先級,在另一個(gè)結(jié)點(diǎn)上要小于這個(gè)值
    advert_int 1        #通告間隔1s
    authentication {
        auth_type PASS  #預(yù)共享密鑰認(rèn)證
        auth_pass 123456    #密碼
    }
    virtual_ipaddress {
        192.168.37.100/24 dev eth0 label eth0:1
    }
    track_script {      #引用腳本
        chk_down
        chk_nginx
    }
    notify_master "/etc/keepalived/notify.sh master"
    notify_backup "/etc/keepalived/notify.sh backup"
    notify_fault "/etc/keepalived/notify.sh fault"
}

vim /etc/keepalived/notify.sh
#!/bin/bash
contact='root@localhost'
notify() {
    mailsubject="$(hostname) to be $1, vip floating"
    mailbody="$(date +'%F %T'): vrrp transition, $(hostname) changed to be $1"
    echo "$mailbody" | mail -s "$mailsubject" $contact
}
case $1 in
master)
    notify master
    ;;
backup)
    notify backup
    systemctl restart nginx
    ;;
fault)
    notify fault
    ;;
*)
    echo "Usage: $(basename $0) {master|backup|fault}"
    exit 1
    ;;
esac

vim /etc/nginx/nginx.conf
http {
    upstream websrvs {
        server 192.168.37.37:80;
        server 192.168.37.47:80;
        least_conn;
    }
    server {
        listen 80;
        location / {
            proxy_pass websrvs;
        }          
    }
}
echo '[ -f /etc/keepalived/down ] && exit 1 || exit 0' > /etc/keepalived/chk_down.sh
echo 'killall -0 nginx &> /dev/null && exit 0 || exit 1' > /etc/keepalived/chk_nginx.sh
chmod +x  "/etc/keepalived/*.sh"
systemctl start keepalived nginx

#client
curl 192.168.37.100
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
禁止轉(zhuǎn)載掠抬,如需轉(zhuǎn)載請通過簡信或評論聯(lián)系作者吼野。
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市两波,隨后出現(xiàn)的幾起案子瞳步,更是在濱河造成了極大的恐慌,老刑警劉巖腰奋,帶你破解...
    沈念sama閱讀 217,657評論 6 505
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件单起,死亡現(xiàn)場離奇詭異,居然都是意外死亡劣坊,警方通過查閱死者的電腦和手機(jī)揉抵,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,889評論 3 394
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來兼砖,“玉大人茧痒,你說我怎么就攤上這事∪裣耄” “怎么了帮寻?”我有些...
    開封第一講書人閱讀 164,057評論 0 354
  • 文/不壞的土叔 我叫張陵,是天一觀的道長赠摇。 經(jīng)常有香客問我固逗,道長浅蚪,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,509評論 1 293
  • 正文 為了忘掉前任烫罩,我火速辦了婚禮惜傲,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘贝攒。我一直安慰自己盗誊,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,562評論 6 392
  • 文/花漫 我一把揭開白布隘弊。 她就那樣靜靜地躺著哈踱,像睡著了一般。 火紅的嫁衣襯著肌膚如雪梨熙。 梳的紋絲不亂的頭發(fā)上开镣,一...
    開封第一講書人閱讀 51,443評論 1 302
  • 那天,我揣著相機(jī)與錄音咽扇,去河邊找鬼邪财。 笑死,一個(gè)胖子當(dāng)著我的面吹牛质欲,可吹牛的內(nèi)容都是我干的树埠。 我是一名探鬼主播,決...
    沈念sama閱讀 40,251評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼嘶伟,長吁一口氣:“原來是場噩夢啊……” “哼怎憋!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起奋早,我...
    開封第一講書人閱讀 39,129評論 0 276
  • 序言:老撾萬榮一對情侶失蹤盛霎,失蹤者是張志新(化名)和其女友劉穎,沒想到半個(gè)月后耽装,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體愤炸,經(jīng)...
    沈念sama閱讀 45,561評論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,779評論 3 335
  • 正文 我和宋清朗相戀三年掉奄,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了规个。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 39,902評論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡姓建,死狀恐怖诞仓,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情速兔,我是刑警寧澤墅拭,帶...
    沈念sama閱讀 35,621評論 5 345
  • 正文 年R本政府宣布,位于F島的核電站涣狗,受9級特大地震影響谍婉,放射性物質(zhì)發(fā)生泄漏舒憾。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,220評論 3 328
  • 文/蒙蒙 一穗熬、第九天 我趴在偏房一處隱蔽的房頂上張望镀迂。 院中可真熱鬧,春花似錦唤蔗、人聲如沸探遵。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,838評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽箱季。三九已至,卻和暖如春领虹,著一層夾襖步出監(jiān)牢的瞬間规哪,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 32,971評論 1 269
  • 我被黑心中介騙來泰國打工塌衰, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人蝠嘉。 一個(gè)月前我還...
    沈念sama閱讀 48,025評論 2 370
  • 正文 我出身青樓最疆,卻偏偏與公主長得像,于是被迫代替她去往敵國和親蚤告。 傳聞我的和親對象是個(gè)殘疾皇子努酸,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,843評論 2 354