nginx從入門到實踐

花了一週時間瞭解nginx相關的知識,主要內容有:php

基礎知識: Nginx的快速部署安裝、模塊、基礎配置語法,Nginx的日誌輸出、Nginx默認配置模塊、Nginx作爲http代理服務,介紹代理服務的類型,正向反向代理配置,nginx做爲的應用層負載均衡服務的各類應用,hash負載均衡策略,Nginx緩存,html

高級知識: Nginx經常使用配置模塊,rewirte的配置語法和規則,配置基於指定地域的規則訪問,geoip模塊、https的實現原理,配置nginx的https服務,secure_link_module的防盜鏈實現,講解,講解Lua的開發語法、配合Nginx實現高效的認證系統和其餘場景。node

架構方面:Nginx常見問題和排錯經驗,實踐應用場景中的方法處理Nginx安全,常見的應用層安全隱患,複雜訪問控制,Nignx的sql防注入安全策略,Nginx的總體配置,搭建合理Nginx中間件架構配置步驟、策略Nginx性能優化:架構優化,操做系統優化、Nginx優化等…linux


基礎知識

環境

初始環境

docker啓動nginx

docker run -d -p 8088:80 --name nginx_8088 nginx_80:latest /sbin/init

四項確認

  • 確認系統網絡(ping)c++

  • 確認yum可用 (yum list | grep gccweb

  • 確認關閉iptables (iptables -F)算法

  • 確認停用selinuxsql

兩項安裝

yum -y install gcc gcc-c++ autoconf pcre pcre-devel make automake
yum -y install wget httpd-tools vim

一次初始化

mkdir -pv /opt/{app,download,logs,work,backup}

nginx安裝

肯定nginx源docker

vim /etc/yum.repos.d/nginx.repo
添加:
[nginx]
name=nginx repo
baseurl=http://nginx.org/packages/centos/$releasever/$basearch/
gpgcheck=0
enabled=1

安裝

yum list | grep nginx
yum install nginx

查看版本

nginx -v

查看nginx 編譯的參數

nginx -V

nginx啓動

nginx -c /etc/nginx/nginx.conf

重啓nginx服務

systemctl restart nginx.service

柔和重啓

nginx -s reload -c /etc/nginx/nginx.conf

檢查配置文件

nginx -t -c /etc/nginx/nginx.conf

中間件架構

paste image

nginx簡述

nginx是一個開源且高性能、可靠的http中間件,代理服務。

Nginx(發音同engine x)是一個 Web服務器,也能夠用做反向代理,負載平衡器和 HTTP緩存。

該軟件由 Igor Sysoev 建立,並於2004年首次公開發布。同名公司成立於2011年,以提供支持。

爲何選擇nginx

io多路複用epoll

多個描述符的i/o操做都能在一個線程內併發交替地順序完成,這就教i/o多路複用,這裏的」複用「指的是複用同一個線程。i/o多路複用的實現方式爲:select、poll、epoll

paste image

什麼是select

paste image

epoll模型

  • 當FD就緒,採用系統的回調函數之間將fd放入,效率更高

  • 最大鏈接無限制

輕量級

  • 功能模塊少

  • 代碼模塊化

cpu親和(affinity)

是一種cpu核心和nginx工做進程綁定方式,把每一個worker進程固定在一個cpu上執行,減小切換cpu的cache miss,得到更好的性能。
paste image

說白了就是減小cpu切換所損耗的性能

sendfile

paste image

nginx版本

  • Mainline version 開發版

  • Stable version 穩定版

  • Legacy version 歷史版本

基本參數使用

rpm

rpm命令是RPM軟件包的管理工具。rpm本來是Red Hat Linux發行版專門用來管理Linux各項套件的程序,因爲它遵循GPL規則且功能強大方便,於是廣受歡迎。逐漸受到其餘發行版的採用。RPM套件管理方式的出現,讓Linux易於安裝,升級,間接提高了Linux的適用度。

安裝目錄

列出服務的安裝目錄



/etc/logrotate.d/nginx
/etc/nginx
/etc/nginx/conf.d
/etc/nginx/conf.d/default.conf
/etc/nginx/fastcgi_params
/etc/nginx/koi-utf
/etc/nginx/koi-win
/etc/nginx/mime.types
/etc/nginx/modules
/etc/nginx/nginx.conf
/etc/nginx/scgi_params
/etc/nginx/uwsgi_params
/etc/nginx/win-utf
/etc/sysconfig/nginx
/etc/sysconfig/nginx-debug
/usr/lib/systemd/system/nginx-debug.service
/usr/lib/systemd/system/nginx.service
/usr/lib64/nginx
/usr/lib64/nginx/modules
/usr/libexec/initscripts/legacy-actions/nginx
/usr/libexec/initscripts/legacy-actions/nginx/check-reload
/usr/libexec/initscripts/legacy-actions/nginx/upgrade
/usr/sbin/nginx
/usr/sbin/nginx-debug
/usr/share/doc/nginx-1.12.2
/usr/share/doc/nginx-1.12.2/COPYRIGHT
/usr/share/man/man8/nginx.8.gz
/usr/share/nginx
/usr/share/nginx/html
/usr/share/nginx/html/50x.html
/usr/share/nginx/html/index.html
/var/cache/nginx
/var/log/nginx


目錄解釋

路徑 類型 做用
/etc/logrotate.d/nginx 配置文件 nginx日誌輪轉,用於logrotate服務的日誌切割
/etc/nginx 
/etc/nginx/conf.d 
/etc/nginx/conf.d/default.conf 
/etc/nginx/nginx.conf
目錄、配置文件 nginx主配置文件
/etc/nginx/fastcgi_params 
/etc/nginx/scgi_params 
/etc/nginx/uwsgi_params
配置文件 cgi配置相關,fastcgi配置
/etc/nginx/koi-utf 
/etc/nginx/koi-win 
/etc/nginx/win-utf
配置文件 編碼映射轉化文件
/etc/nginx/mime.types 配置文件 設置http協議的Content-Type與擴展名對應關係
/etc/sysconfig/nginx 
/etc/sysconfig/nginx-debug 
/usr/lib/systemd/system/nginx-debug.service 
/usr/lib/systemd/system/nginx.service
配置文件 用於配置出系統守護進程管理器管理方式
/etc/nginx/modules 
/usr/lib64/nginx/modules
目錄 nginx模塊目錄
/usr/sbin/nginx 
/usr/sbin/nginx-debug
命令 nginx服務的啓動管理的終端命令
/usr/share/doc/nginx-1.12.2 
/usr/share/doc/nginx-1.12.2/COPYRIGHT 
/usr/share/man/man8/nginx.8.gz
文件目錄 nginx的手冊和幫助文件
/var/cache/nginx 目錄 nginx的緩存目錄
/var/log/nginx 目錄 nginx的日誌目錄

編譯參數

列出編譯參數的命令

nginx version: nginx/1.12.2
built by gcc 4.8.5 20150623 (Red Hat 4.8.5-16) (GCC) 
built with OpenSSL 1.0.2k-fips  26 Jan 2017
TLS SNI support enabled
configure arguments: 
--prefix=/etc/nginx  \
--sbin-path=/usr/sbin/nginx \
--modules-path=/usr/lib64/nginx/modules \
--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 \
--http-client-body-temp-path=/var/cache/nginx/client_temp \
--http-proxy-temp-path=/var/cache/nginx/proxy_temp \
--http-fastcgi-temp-path=/var/cache/nginx/fastcgi_temp \
--http-uwsgi-temp-path=/var/cache/nginx/uwsgi_temp \
--http-scgi-temp-path=/var/cache/nginx/scgi_temp \
--user=nginx --group=nginx \
--with-compat \
--with-file-aio \
--with-threads \
--with-http_addition_module \
--with-http_auth_request_module \
--with-http_dav_module \
--with-http_flv_module \
--with-http_gunzip_module \
--with-http_gzip_static_module \
--with-http_mp4_module \
--with-http_random_index_module \
--with-http_realip_module \
--with-http_secure_link_module \
--with-http_slice_module \
--with-http_ssl_module \
--with-http_stub_status_module \
--with-http_sub_module \
--with-http_v2_module \
--with-mail \
--with-mail_ssl_module \ 
--with-stream \
--with-stream_realip_module \
--with-stream_ssl_module \
--with-stream_ssl_preread_module \
--with-cc-opt='-O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector-strong \
--param=ssp-buffer-size=4 -grecord-gcc-switches -m64 -mtune=generic -fPIC' \
--with-ld-opt='-Wl,-z,relro -Wl,-z,now -pie'


參數解釋

路徑 類型
–prefix=/etc/nginx 
–sbin-path=/usr/sbin/nginx 
–modules-path=/usr/lib64/nginx/modules 
–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
安裝目的目錄或路徑
–http-client-body-temp-path=/var/cache/nginx/client_temp 
–http-proxy-temp-path=/var/cache/nginx/proxy_temp
–http-fastcgi-temp-path=/var/cache/nginx/fastcgi_temp 
–http-uwsgi-temp-path=/var/cache/nginx/uwsgi_temp
–http-scgi-temp-path=/var/cache/nginx/scgi_temp
執行對應模塊時,nginx所保留的臨時性文件
–user=nginx –group=nginx 設定nginx進程啓動的用戶和組用戶
–with-cc-opt=parameters 設置額外的參數將被添加到CFLAGS變量
–with-ld-opt=parameters 設置附加的參數,連接系統庫

nginx基本配置語法

http相關

展現每次請求的請求頭

curl -v http://www.baidu.com

結果

% Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
  0     0    0     0    0     0      0      0 --:--:-- --:--:-- --:--:--     0* About to connect() to www.baidu.com port 80 (#0)
*   Trying 61.135.169.121...
* Connected to www.baidu.com (61.135.169.121) port 80 (#0)
> GET / HTTP/1.1
> User-Agent: curl/7.29.0
> Host: www.baidu.com
> Accept: */*
> 
< HTTP/1.1 200 OK
< Server: bfe/1.0.8.18
< Date: Thu, 30 Nov 2017 02:14:02 GMT
< Content-Type: text/html
< Content-Length: 2381
< Last-Modified: Mon, 23 Jan 2017 13:27:32 GMT
< Connection: Keep-Alive
< ETag: "588604c4-94d"
< Cache-Control: private, no-cache, no-store, proxy-revalidate, no-transform
< Pragma: no-cache
< Set-Cookie: BDORZ=27315; max-age=86400; domain=.baidu.com; path=/
< Accept-Ranges: bytes
< 
{ [data not shown]
100  2381  100  2381    0     0  88266      0 --:--:-- --:--:-- --:--:-- 91576
* Connection #0 to host www.baidu.com left intact

nginx日誌類型

  • error.log、 access.log

  • log_format

格式

syntax: log_format name [escape=default | json] string...;
default: log_format combined "...";
context:http

nginx變量

nginx配置的內容

user  nginx;
worker_processes  1;
error_log  /var/log/nginx/error.log warn;
pid        /var/run/nginx.pid;
events {
    worker_connections  1024;
}
http {
    include       /etc/nginx/mime.types;
    default_type  application/octet-stream;
    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  /var/log/nginx/access.log  main;
    sendfile        on;
    #tcp_nopush     on;
    keepalive_timeout  65;
    #gzip  on;
    include /etc/nginx/conf.d/*.conf;
}

變量類型

  • http請求變量:arg_PARAMETER,http_header,sent_http_header

  • 內置變量:nginx內置的

  • 自定義變量: 本身定義

nginx模塊

  • nginx官方模塊

  • 第三方模塊

default.conf

server {
    listen       80;
    server_name  localhost;
    #charset koi8-r;
    #access_log  /var/log/nginx/host.access.log  main;
    location / {
        root   /usr/share/nginx/html;
        index  index.html index.htm;
    }
    #error_page  404              /404.html;
    # redirect server error pages to the static page /50x.html
    #
    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /usr/share/nginx/html;
    }
    # proxy the PHP scripts to Apache listening on 127.0.0.1:80
    #
    #location ~ \.php$ {
    #    proxy_pass   http://127.0.0.1;
    #}
    # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
    #
    #location ~ \.php$ {
    #    root           html;
    #    fastcgi_pass   127.0.0.1:9000;
    #    fastcgi_index  index.php;
    #    fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;
    #    include        fastcgi_params;
    #}
    # deny access to .htaccess files, if Apache's document root
    # concurs with nginx's one
    #
    #location ~ /\.ht {
    #    deny  all;
    #}
}

nginx開啓的模塊

--with-compat 
--with-file-aio 
--with-threads 
--with-http_addition_module 
--with-http_auth_request_module 
--with-http_dav_module 
--with-http_flv_module 
--with-http_gunzip_module 
--with-http_gzip_static_module 
--with-http_mp4_module 
--with-http_random_index_module 
--with-http_realip_module 
--with-http_secure_link_module 
--with-http_slice_module 
--with-http_ssl_module 
--with-http_stub_status_module 
--with-http_sub_module 
--with-http_v2_module 
--with-mail 
--with-mail_ssl_module 
--with-stream 
--with-stream_realip_module 
--with-stream_ssl_module 
--with-stream_ssl_preread_module

安裝編譯模塊

編譯選項 做用
–with-http_stub_status_module nginx的客戶端狀態
–with-http_random_index_module 目錄中選擇一個隨機主頁
–with-http_sub_module http內容替換
–limit_conn_module 鏈接頻率限制
–limit_req_module 請求頻率限制
http_access_module 基於ip的訪問控制
http_auth_basic_module 基於用戶的信任登陸

http_stub_status_module 配置

配置語法

syntax: stub_status;
default:-
context:server, location

在default.conf中添加:

# my config
location /mystatus {
stub_status;
}

檢查和從新啓動配置

nginx -tc /etc/nginx/nginx.conf

重啓服務

nginx -s reload -c /etc/nginx/nginx.conf

檢查效果
輸入:http://127.0.0.1:8088/mystatus

paste image

表示nginx的活躍鏈接數;握手的總次數、處理鏈接數;讀、寫、等待個數

http_random_index_module

配置語法

syntax: random_index on | off;
default:random_index off;
context:location

在default.conf中將下面的配置:

location / {
root   /usr/share/nginx/html;
index  index.html index.htm;
}

改成:

location / {
root   /usr/share/nginx/html;
random_index on;
#index  index.html index.htm;
}

重啓後多刷幾回網頁:

paste image

主頁出現不一樣了。

paste image

http_sub_module (替換)

配置語法

syntax: sub_filter string replacement;
default:-
context:http,server,location
syntax: sub_filter_last_modified on | off (重要用戶緩存)
default:sub_filter_last_modified off;
context:http,server,location

syntax: sub_filter_once on | off 
default:sub_filter_once on;
context:http,server,location

是否只替換一次

鏈接限制

壓力測試

ab -n 50 -c 20 http://127.0.0.1/index.html

-n 表示請求次數
-c 表示併發數

配置語法

鏈接限制

syntax: limit_conn_zone key zone=name:size;
default:-
context:http
syntax:limit_conn zone number;
default:-
context:http, server, location

請求限制

syntax: limit_req_zone key zone=name:size rate=rate;
default:-
context:http

syntax: limit_req_zone name [burst=number] [nodelay];
default:-
context:http,server,location

在default.conf中將下面的配置:

server {
    listen       80;
    server_name  localhost;
    #charset koi8-r;
    #access_log  /var/log/nginx/host.access.log  main;
    location / {
        root   /usr/share/nginx/html;
        index  index.html index.htm;
    }
    # my config
    location /mystatus {
        stub_status;
    }
    #error_page  404              /404.html;
    # redirect server error pages to the static page /50x.html
    #
    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /usr/share/nginx/html;
    }
    # proxy the PHP scripts to Apache listening on 127.0.0.1:80
    #
    #location ~ \.php$ {
    #    proxy_pass   http://127.0.0.1;
    #}
    # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
    #
    #location ~ \.php$ {
    #    root           html;
    #    fastcgi_pass   127.0.0.1:9000;
    #    fastcgi_index  index.php;
    #    fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;
    #    include        fastcgi_params;
    #}
    # deny access to .htaccess files, if Apache's document root
    # concurs with nginx's one
    #
    #location ~ /\.ht {
    #    deny  all;
    #}
}

改成:

limit_conn_zone $binary_remote_addr zone=conn_zone:1m;
limit_req_zone $binary_remote_addr zone=req_zone:1m rate=1r/s;
server {
    listen       80;
    server_name  localhost;
    #charset koi8-r;
    #access_log  /var/log/nginx/host.access.log  main;
    location / {
        root   /usr/share/nginx/html;
        #limit_conn conn_zone 1;
        limit_req zone=req_zone;
        # limit_req zone=req_zone burst nodelay;
        # limit_req zone=req_zone burst nodelay;
        index  index.html index.htm;
    }
    # my config
    location /mystatus {
        stub_status;
    }
    #error_page  404              /404.html;
    # redirect server error pages to the static page /50x.html
    #
    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /usr/share/nginx/html;
    }
    # proxy the PHP scripts to Apache listening on 127.0.0.1:80
    #
    #location ~ \.php$ {
    #    proxy_pass   http://127.0.0.1;
    #}
    # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
    #
    #location ~ \.php$ {
    #    root           html;
    #    fastcgi_pass   127.0.0.1:9000;
    #    fastcgi_index  index.php;
    #    fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;
    #    include        fastcgi_params;
    #}
    # deny access to .htaccess files, if Apache's document root
    # concurs with nginx's one
    #
    #location ~ /\.ht {
    #    deny  all;
    #}

壓測結果

限制前
paste image

限制後
paste image

http_access_module

配置語法

syntax: allow address | CIDR | unix: | all
default:-
context:http,server,location,limit_except

syntax:deny address | CIDR | unix: | all
default:-
context:http, server, location ,limit_except

測試
配置以下

location ~ ^/admin.html {
  root /opt/app/code;
  deny all;
  index index.html index.htm;
}

結果
paste image

侷限性

paste image

http_x_forwarded_for

paste image

http_x_forwarded_for = client ip, proxy(1)ip,proxy(2)ip,…

解決方法

  • 採用別的http頭信息控制訪問,如http_x_forward_for

  • 結合geo模塊操做

  • 經過http自定義變量傳遞

http_auth_basic_module

配置語法

syntax: auth_basic string | off;
default:-
context:http,server,location,limit_except
syntax:auth_basic_user_file file;
default:-
context:http, server, location ,limit_except

生成password文件

htpasswd -c ./auth_conf wujunqi

修改conf文件

location ~ ^/admin.html {
  root /opt/app/code;
  auth_basic "please input you user name and passwd";
  auth_basic_user_file /etc/nginx/auth_conf;
  index index.html index.htm;
}

測試

paste image

侷限性
  • 用戶信息依賴文件方式

  • 操做管理機械、效率低下

解決方案
  • nginx 結合LUA實現高效驗證

  • nginx和LDAP打通,利用nginx-auth-ldap模塊

場景實踐

靜態資源web服務

靜態資源

定義

非服務器動態生成的文件

paste image

paste image

靜態資源服務場景-CDN

paste image

文件讀取配置

sendfile

syntax: sendfile on | off;
default:sendfile off
context:http,server,location,if in location

–with-file-aio異步文件讀取

tcp_nopush

做用:sendfile 開啓的狀況下,提升網絡包的傳輸效率(等待,一次傳輸)

syntax:tcp_nopush on | off
default:tcp_nopush off
context:http, server, location

相反的

syntax:tcp_nodelay on | off
default:tcp_nodelay on
context:http, server, location

做用
在keepalive鏈接下,提升網絡包的傳輸實時性

壓縮

做用

壓縮傳輸

syntax:gzip on | off
default:gzip off
context:http, server, if in location

syntax:gzip_comp_level level;
default:gzip_comp_level 1;
context:http, server, location

擴展nginx壓縮模塊

  • http_gzip_static_module:預讀gzip功能

  • http_gunzip_module: 應用支持gunzip的壓縮方式

配置截圖

paste image

瀏覽器緩存

http協議定義的緩存機制(如:expires,cache-control 等)

  • 瀏覽器無緩存

paste image

  • 瀏覽器有緩存

paste image

檢測過時機制

做用 請求頭
檢驗是否過時 expires, cache-control (max-age)
協議中Etag頭信息校驗 etag
last-modified 頭信息校驗 last-modified

瀏覽器請求服務器過程(緩存版本)

paste image

相關配置

expires

添加cache-control、expires頭

syntax: expires [modified] time;
expires epoch | max | off;
default: expires off;
context:http, server, location

配置例子

paste image

跨域訪問

paste image

爲何瀏覽器禁止跨域訪問

不安全,容易出現CSRF***

paste image

nginx配置

syntax: add_header name value [always]
default: -
context:http, server, location, if in location

添加請求頭:Access-Control-Allow-Origin

配置截圖

paste image

防盜鏈

目的

防止資源被盜用

防盜鏈設置思路

首要方式:區別哪些請求是非正常的用戶請求

基於http_refer防盜鏈配置模塊

syntax: valid_referers none | blocked | server_names | string...;
default: -
context:server, location

配置截圖

paste image

none:表示若是沒帶refer
blocked:表明不是標準的http寫過過來的

一個命令

curl -e "http://www.baidu.com" -I http://116.62.103.228/wei.png

-e:表示refer
-i:表示只顯示請求頭

代理服務

代理-代爲辦理(代理理財、代理收貨等)

paste image

代理服務

paste image

代理區別

區別在於代理的對象不同

  • 正向代理的對象是客戶端

  • 反向代理代理的是服務器

正向代理

paste image

反向代理

paste image

代理的配置

syntax: proxy_pass URL;
default: -
context:location, if in location, limit_except

url通常爲:

反向代理配置截圖

paste image

想訪問8080,只能訪問到80,經過80而後經過反向代理能夠訪問到8080

正向代理配置截圖

paste image

116.62.103.228的配置以下(其實和反向代理配置參很少)

paste image

客戶端配置

paste image

緩存區配置

syntax: proxy_buffering on | off
default: proxy_buffering on
context:location,http,server

擴展

  • proxy_buffer_size

  • proxy_buffers

  • proxy_busy_buffers size

跳轉重定向配置

syntax: proxy_redirect default;proxy_redirect off;proxy_redirect redirect replacement;
default: proxy_redirect default;
context:location,http,server

頭信息配置

syntax: proxy_set_header field value;
default: proxy_set_header host $proxy_host
 proxy_set_header connection close;
context:location,http,server

超時配置

syntax: proxy_connect_timeout time;
default: proxy_connect_timeout 60s;
context:location,http,server

擴展

  • proxy_read_timeout

  • proxy_send_timeout

總的配置

paste image

負載均衡調度器 SLB

nginx負載均衡

paste image

GSLB

GSLB 是英文Global Server Load Balance的縮寫,意思是全局負載均衡。做用:實如今廣域網(包括互聯網)上不一樣地域的服務器間的流量調配,保證使用最佳的服務器服務離本身最近的客戶,從而確保訪問質量。

paste image

SLB

負載均衡(Server Load Balancer,簡稱SLB)是一種網絡負載均衡服務,針對阿里雲彈性計算平臺而設計,在系統架構、系統安全及性能,擴展,兼容性設計上都充分考慮了彈性計算平臺雲服務器使用特色和特定的業務場景。

4層負載均衡

paste image

在iso模型中的傳輸層(包的轉發)

7層負載均衡

paste image

在應用層實現

nginx實現的負載均衡(7層)

paste image

配置

syntax: upstream name{...}
default: -
context:http
配置截圖

paste image

upstream舉例

upstream backend {
server backend1.example.com weight=5;
    server backend2.example.com:8080;
    server unix:/tmp/backend3;
    
    server backup1.exmple.com:8080 backup;
    server backup2.example.com:8080 backup;
}

後端服務器在負載均衡調度中的狀態

字段 做用
down 當前的server暫時不參與負載均衡
backup 預留的備份服務器
max_fails 容許請求失敗的次數
fail_timeout 通過max_fails失敗後,服務暫停的時間
max_conns 限制最大的接收的鏈接數

配置截圖

paste image

調度算法

字段 做用
輪詢 按時間順序逐一分配到不一樣的後端服務器
加權輪詢 weight值越大,分配到的訪問概率越高
ip_hash 每一個請求按訪問ip的hash結果分配,這樣來自同一個ip的固定訪問一個後端服務器
least_conn 最少連接數,那個機器鏈接數少就分發
url_hash 按照訪問的url的hash結果來分配請求,是每一個url定向到同一個後端服務器
hash關鍵值 hash自定義的key

iphash

paste image

url——hash

paste image

配置語法

url_hash

syntax: hash key [consistent];
default:-
context:upstream
this directive appeared in version 1.7.2

配置截圖

paste image

動態緩存

緩存的類型

paste image

代理緩存

paste image

proxy_cache配置語法

syntax: proxy_cache_path path [levels=levels]
Default:-
context:http

開關

syntax: proxy_cache zone | off;
default:proxy_cache off;
context:http, sercer, location

過時週期

syntax: proxy_cache_valid[code] time;
default:-
context:http, sercer, location

緩存的維度

syntax: proxy_cache_key string;
default: proxy_cache_key $scheme$proxy_host$request_uri;
context:http,server,location

配置截圖

paste image

level:目錄分級
inactive:不活躍就清理

如何清理指定緩存

  • rm-rf緩存目錄內容

  • 第三方擴展模塊ngx_cache_purge

如何讓部分頁面不緩存

syntax : proxy_no_cache string ...;
default: -;
context:http,server,location

配置截圖

paste image

大文件分片請求

syntax : slice size
default: slice o
context:http,server,location

http_slice_module

paste image

優點

  • 每一個子請求收到的數據都會造成一個獨立的文件,一個請求斷了,其它請求不受到影響

缺點

  • 當文件很大或者slice很小的時候, 可能會致使文件描述符耗盡等狀況。

深度學習

動靜分離

經過中間件將動態請求和靜態請求分離

爲何

  • 分離資源,減小沒必要要的請求消耗,減小請求延時

paste image

場景

paste image

rewrite規則

應用場景

  • url訪問跳轉,支持開發設計

    • 頁面跳轉、兼容性支持、展現效果等

  • seo優化

  • 維護

    • 後臺維護、流量轉發

  • 安全

配置語法

syntax: rewrite regex replacement [flag];
default:-
context:server, location,if

維護頁面實例

rewrite ^(.*)$ /pages/maintain.html break;

flag

字段 做用
last 中止rewrite檢測
break 中止rewrite檢測
redirect 返回302臨時重定向,地址欄會顯示跳轉後的地址
permanent 返回301永久重定向,地址欄會顯示跳轉後的地址(瀏覽器下次直接訪問重定向後的地址

paste image

paste image

一些實例

paste image

rewrite規則優先級

  • 執行server塊的rewrite指令

  • 執行location匹配

  • 執行指定的locaiton中的rewrite

nginx高級模塊

secure_link_module模塊

  • 制定並容許檢查請求的連接的真實性以及保護資源免遭未經受權的訪問。

  • 限制連接生效週期

syntax: secure_link expression
default:-
context:server, location,server
syntax: secure_link_md5 expression
default:-
context:server, location,http

圖示

paste image

paste image

配置例子

paste image

http_geoip_module使用場景

基於ip地址匹配MaxMind GeoIp 二進制文件,讀取ip所在地域信息

yum install nginx-module-geoip
  • 區別國內外作http訪問規則

  • 區別國內城市地域作http訪問規則

配置截圖

paste image

https服務

對傳輸內容進行加密以及身份驗證。

爲何須要https

  • 傳輸數據被中間人盜用,信息泄露

  • 數據內容劫持,篡改

對稱加密和非對稱加密

paste image

paste image

https加密協議原理

paste image

中間人僞造客戶端和服務器

paste image

如何解決

paste image

生成密鑰和CA證書

安裝openssl和http_ssl_module模塊

#openssl version
openSSL 1.0.1e-fips 11 feb 2013
#nginx -V
--with-http_ssl_module

步驟

  • 生成key密鑰

openssl genrsa -idea -out jesonc.key 1024

結果

paste image

  • 生成證書籤名請求文件(csr文件)

openssl req -new -key jesonc.key -out jesonc.csr

結果
paste image

  • 生成證書籤名文件(CA文件)

openssl x509 -req -days 3650 -in jesonc.csr -signkey jesonc.key -out jesonc.crt

結果

paste image

相關實驗

配置docker(443)

docker run -d -p 443:443 --name nginx_443 nginx_443:latest /sbin/init
nginx -c /etc/nginx/nginx.conf

conf文件配置

server {
    listen       443;
    server_name  localhost;
    ssl on;
    ssl_certificate /etc/nginx/ssl_key/jesonc.crt;
    ssl_certificate_key /etc/nginx/ssl_key/jesonc.key;
    location / {
        root   /usr/share/nginx/html;
        #limit_conn conn_zone 1;
        #limit_req zone=req_zone;
        # limit_req zone=req_zone burst nodelay;
        # limit_req zone=req_zone burst nodelay;
        index  index.html index.htm;
    }
    # my config
    location /mystatus {
        stub_status;
    }
    #error_page  404              /404.html;
    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /usr/share/nginx/html;
    }
}

測試結果

paste image

paste image

https服務優化

  • 激活keepalive長鏈接

  • 設置ssl session緩存

配置截圖

paste image

Nginx架構

之後補上

摘自:http://fanqieto.top/2017/11/29/nginx%E4%BB%8E%E5%85%A5%E9%97%A8%E5%88%B0%E5%AE%9E%E8%B7%B5/
相關文章
相關標籤/搜索