nginx的入門到框架設計


mac上安裝nginx

安裝與啟動

安裝

brew install nginx

命令

通過 Homebrew 下載的軟件默認位置在 /usr/local/Cellar

應該ln-s 加連接就能全局

nginx -h 查看 nginx 命令參數 
nginx -s reopen | quit | reload | stop 開啟 退出 重啟 停止 
nginx -t 測試配置文件是否正確
安裝:brew install nginx      或者      sudo brew install nginx

啟動:brew services start nginx       或者         sudo brew services start nginx

重啟:brew services restart nginx        或者         sudo brew services restart nginx

停止:brew services stop nginx           或者            sudo brew services stop nginx

查看:cat /usr/local/etc/nginx/nginx.conf

編輯:vi /usr/local/etc/nginx/nginx.conf

/usr/local/var/www (服務器默認路徑)

nginx -t -c /etc/nginx/nginx.conf 可以檢查配置
nginx -s reload -c /etc/nginx/nginx.conf 重新導入配置

Nginx 默認8080端口

簡單配置-設置緩存-配置https

include servers/*.conf;  include可以添加子文件  

#http進來的轉發發https
server {
    # 域名進來
    listen 80 default_server;
    # ip進來
    listen [::]:80 default_server;
    server_name test.com
    # 重定向到https
    return 302 https://$server_name$redirect_uri
}


# 設置緩存
proxy_cache_path cache levels=1:2 keys_zone=my_test_cache:10m;
# /usr/local/var/www
server {
    listen 8081;
    # 通過host來判斷進入那個配置,那樣端口80就可以代理到不同的地方
    server_name test.com;

    #
    charset koi8 - r;

    # 日志
    access_log logs / host.access.log main;

    # 代理
    location / {
        # 使用代理緩存
        proxy_cache my_test_cache;
        proxy_pass http://127.0.0.1:8888;
        # 重寫host,不然通過nginx,會把瀏覽器的頭改成中間代理
        proxy_set_header Host $host;
    }

    #
    error_page 404 / 404. html;

    #
    redirect server error pages to the static page / 50 x.html#
    error_page 500 502 503 504 / 50 x.html;
    location = /50x.html {
        root html;
    }
}


server{
#比起默認的80 使用了443 默認 是ssl方式  多出default之后的ssl
   listen 443 default ssl;
#default 可省略
#開啟  如果把ssl on;這行去掉,ssl寫在443端口后面。這樣http和https的鏈接都可以用
    ssl on;
#證書(公鑰.發送到客戶端的)
    ssl_certificate ssl/server.crt;
#私鑰,
    ssl_certificate_key ssl/server.key;
#下面是綁定域名
    server_name www.baidu.com;
    location / {
#禁止跳轉
     proxy_redirect off;
#代理淘寶
proxy_pass https://www.tao.com/;  
    }        
}

學習課程的前提准備

//安裝擴展
yum -y install gcc gcc-c++ autoconf pcre pcre-devel make automake
//安裝工具
yum -y install wget httpd-tools vim
//初始化目錄
cd /opt;mkdir app download logs work backup
//查看安裝
yum list | grep gcc
//查看iptables的列表
iptables -L
//關閉iptables
iptables -F
iptables -t nat -L
iptables -t nat -F
getenforce

nginx基礎

nginx的中間件架構

image

nginx簡述

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

常見的http服務

  • httpd-Apache基金會
  • iis-微軟
  • gws-google

為什么選擇nginx

原因1、IO多路復用epoll

  1. 什么IO多路復用
    多個描述符的I/O操作都能在一個線程內並發交替地順序完成,這就是叫I/O多路復用,這里復用指的就是復用一個線程
  2. 什么事epoll
    IO多路復用的實現方式select、poll、epoll
    image
  • slect的缺點

    1、能夠監視文件描述符的數量存在最大限制2、線性掃描效率低下

  • epoll模型

    1、每當FD就緒,采用系統的回調函數之間將fd放入,效率更高2、最大連接無限制

原因2、輕量級

  • 功能模塊少
  • 代碼模塊化

原因3、cpu親和

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

原因3、sendfile

image

image

nginx安裝

1、一般使用穩定版安裝
新建yum源
vim /etc/yum.repos.d/nginx.repo

新建的內容,修改系統和系統版本
[nginx]
name=nginx repo
baseurl=http://nginx.org/packages/centos/7/$basearch/
gpgcheck=0
enabled=1


可以查看 yum list | grep nginx

安裝  yum install nignx

nginx -v
2、安裝目錄
命令 rpm -ql nginx

/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.14.0
/usr/share/doc/nginx-1.14.0/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

image
image
image
image
image
image
image
image
image
image
image

3、編譯參數
nginx -V

nginx version: nginx/1.14.0
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'

image
image
image
image
image

4、nginx基本配置語法
#user  nobody;
worker_processes  1;

#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;

#pid        logs/nginx.pid;


events {
    worker_connections  1024;
}


http {
    include       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  logs/access.log  main;

    sendfile        on;
    #tcp_nopush     on;

    #keepalive_timeout  0;與客戶端的連接時間
    keepalive_timeout  65;
    
    #gzip  on; 
    
    #可以定義多個server
    server {
        listen       80;
        server_name  localhost;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

        location /api{
            proxy_pass http://127.0.0.1:3000;
        }
    	location /{
    	    root /home/chenjinxin/www/weather-hl/datanews/;
    	}

        #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   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;
        #}
    }


    # another virtual host using mix of IP-, name-, and port-based configuration
    #
    #server {
    #    listen       8000;
    #    listen       somename:8080;
    #    server_name  somename  alias  another.alias;

    #    location / {
    #        root   html;
    #        index  index.html index.htm;
    #    }
    #}


    # HTTPS server
    #
    #server {
    #    listen       443 ssl;
    #    server_name  localhost;

    #    ssl_certificate      cert.pem;
    #    ssl_certificate_key  cert.key;

    #    ssl_session_cache    shared:SSL:1m;
    #    ssl_session_timeout  5m;

    #    ssl_ciphers  HIGH:!aNULL:!MD5;
    #    ssl_prefer_server_ciphers  on;

    #    location / {
    #        root   html;
    #        index  index.html index.htm;
    #    }
    #}

}
5、http請求

客戶端與服務端交互
request 包括請求行、請求頭部、請求數據
response 包括狀態行、信息報頭、響應正文

6、nginx日志狀態

包括:error.log(error級別) access_log(每一次訪問)

  1. 使用log_format來配置
  2. 位置只能配置在http下面
#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;
#access_log  logs/host.access.log  main; 可以通過內置變量來保存成特定的格式
7、nginx變量
  • HTTP請求- arg_PARAMETER http_HEADER sent_http_HEADER
  • 內置變量- Nginx內置的 自己查
  • 自定義變量- 自己定義
    # 定義一個main在access_log 記錄
    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                     '"$http_user_agent" "$http_x_forwarded_for"';

    access_log  logs/access.log  main;
8、nginx模塊講解
  1. 官方模塊
--with-http_stub_status_module  nginx的客戶端狀態
http_stub_status_module的配置
syntax: stub_status;
default: 無;
context: server, location

lccation /mystatus{
    stub_status;
}

--with-http_random_index_module 目錄中選擇一個隨機主頁
random_index_module的配置
syntax: random_index on | off;
default: random_index off;
context: location

location / {
    root /usr/share/nginx/html;
    random_index on;
}

---with-http_sub_module  HTTP內容替換
http_sub_module的配置
syntax: sub_filter string(要替換的內容) replacement(替換的內容);
default: 無;
context: http,server,loaction

location /{
    root /opt/app/code;
    index index.html index.html;
    sub_filter '<a>c' '<a>d';//只替換了一個
    sub_filter_once off;//全替換
}

syntax: sub_filter_last_modified on | off; // 校驗last_modified
default: sub_filter_last_modified off;
context: http,server,loaction

syntax: sub_filter_once on | off; // 是匹配第一個還是所有都匹配,on就是第一行
default: sub_filter_once on;
context: http,server,loaction
  1. 第三方模塊
nginx的請求限制

連接頻率限制 - limit_conn_module
請求頻率限制 - limit_req_module

http協議版本 連接關系
http1.0 tcp不能復用
http1.1 順序性tcp復用 主流
http2.0 多路復用tcp復用
  • http請求建立在一次tcp連接基礎上
  • 一次tcp請求至少產生一次http連接

限制連接

syntax: limit_conn_zone key zone=name:size; // key可以是ip等,zone就是空間的名字  size就是大小比如20m
default: 無;
context: http

syntax: limit_conn zone number; // 配合上面定義的zone的名字 number就是數量
default: 無;
context: http,server,location

請求限制

syntax: limit_req_zone key zone=name:size rate=rate; // key可以是ip等,zone就是空間的名字  size就是大小比如20m rate是速率
default: 無;
context: http

syntax: limit_req zone=name [burst=number][nodelay]; // 配合上面定義的zone的名字 number就是數量
default: 無;
context: http,server,location
limit_conn_zone $binanry_remote_addr zone=conn_zone:1m;
limit_req_zone $binary_remtoe_addr zone=req_zone:1m rate=1r/s;

location / {
    root /opt/app/code;
    limit_conn conn_zone 1;
    #limit_req zone=req_zone burst=3 nodelay;
    #limit_req zone=req_zone burst=3;
    #limit_req zone=req_zone;
}

Nginx的訪問控制

  • 基於ip的訪問控制 - http_access_module
  • 基於用戶的信任登錄 - http_auth_basic_module
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 222.128.189.17;
    allow all;
    index index.html index.html;
}

局限性

image

通過代理訪問,ip1別ip2替代

image

http_x_forwarded_for = Client IP, Proxy(1) IP, Proxy(2) IP, ..

解決的方法

  1. 采用別的http頭信息控制訪問,如:HTTP_X_FORWARD_FOR
  2. 結合geo模式
  3. 通過HTTP自定義變量傳遞
http_auth_basic_module
syntax: auth_basic string | off;
default: auth_basic off;
context: http,server,location,limit_except
syntax: auth_basic_user_file file;
default: ;
context: http,server,location,limit_except

例子

location ~ ^/admin.html {
    root /opt/app/code;
    auth_basic "Auth access test!input your password!";
    auth_basic_user_file /etc/nginx/auth_conf;# 文件
    index index.html index.html;
}

局限性

  • 用戶信息依賴文件方式
  • 操作管理機械,效率低下

解決方案

  • nginx解決lua實現高效驗證
  • nginx和ldap打通,來解決

進階學習

  1. 靜態資源web服務
  2. 代理服務
  3. 負載均衡調度器SLB
  4. 動態緩存

十、靜態資源web服務

一般的web服務

image

靜態資源服務cdn
配置語法----文件讀取
syntax: sendfile on|off;
default: sendfile off;
context: http,server,location,if in location

引讀:----with-file-aio 異步文件讀取

配置語法----tcp_nopush
syntax: tcp_nopush on|off;
default: tcp_nopush off;
context: http,server,location

作用:Sendfile開啟的情況下,提高網絡包的傳輸效率

配置語法----tcp_nodelay
syntax: tcp_nodelay on|off;
default: tcp_nodelay on;
context: http,server,location

作用:keepalive聯系下,提高網絡包的傳輸實時性

配置語法----壓縮
syntax: gzip on|off;
default: gzip off;
context: http,server,location,if in location

壓縮比例

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

gzip版本

syntax: gzip_http_version 1.0|1.1;
default: gzip_http_version 1.1;
context: http,server,location
http_gzip_static_module - 預讀gzip功能
http_gunzip_module - 應用支持gunzip的壓縮方式

作用:壓縮傳輸

瀏覽器緩存

HTTP協議定義的緩存機制(如: expires; cache-control)

image

配置語法----expires

添加cache-control expires

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

max-age=0 都會請求服務器,瀏覽器有時會自己加

跨域訪問

nginx怎么做 access-control-allow-origin

syntax:add_header name value [always]
default: ;
context: http, server, location, if in location
防盜鏈

目的:防止資源被盜用

  • 簡單放盜鏈

基於http_refer防盜鏈的方式

location {
    valid_referers none blocked 116.62.103.228;
    if ($invalid_referer) {
        return 403;
    }
}
代理服務

代理----代未辦理
image

正向代理

image

vpn的原理

反向代理

image

代理區別

區別在於代理的對象不一樣

正向代理代理的對象時客戶端
反向代理代理的對象時服務端

syntax:proxy_pass url
default: ;
context: location, if in location,limit_except

正向代理的例子

location / {
    proxy_pass http://$http_host$request_uri
}

其他的配置語法

緩沖區

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

擴展:proxy_buffer_size/ proxy_buffers/ proxy_buffers_size

跳轉重定向

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

頭信息

syntax:proxy_set_header field value;
default: proxy_set_header Host $proxy_host; proxy_set_header Connection close;
context: http, server, location

擴展:proxy_hide_header / proxy_set_body

超時

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

例子

image

三、nginx負載均衡

image

GSLB 全局負載均衡

image

SLB

image

基於LVS的中間件架構

四層負載均衡

image

七層負載均衡 保存應用層 nginx就是典型的

image

nginx的實現

image

syntax: upstream name {...};
default: ;
context: http

例子

upstream chen {
    server 116.62,103.228:8001;
    server 116.62,103.228:8002;
    server 116.62,103.228:8003;
}

server {
    location / {
        proxy_pass http://chen;
        include proxy_params;
    }
}

upstream舉例

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

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

參數 說明
down 當前的server暫時不參與負載均衡
backup 預留的備份服務器
max_fails 允許請求失敗的次數
fail_timeout 經過max_fails失敗后,服務暫停的時間
max_conns 限制最大的接收的連接數,針對服務器配置不一致

調度算法

算法 說明
輪詢 按時間順序逐一分配到不同的后端服務器
加權輪詢 wright值越大,分配到的訪問幾率越大
ip_hash 每一個請求按訪問ip的hash結果分配,這樣來自通一個ip的固定訪問一個后端服務器
least_conn 最少連接數,那個機器連接數少就分發
url_hash 按照訪問的url的hash結果來分配請求,是每個url定向到同一個后端服務器
hash關鍵數值 hash自定義的key

緩存

1、緩存類型

  • 服務端緩存比如radis
  • 代理緩存比如在nginx里做
  • 客戶端緩存

2、代理緩存

image

3、proxy_cache配置語法

syntax:proxy_cahe_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];
default: ;
context: ;

4、配置緩存過期周期

syntax:proxy_cache_valid [code ...] time;
default: ;
context: server.location;

5、配置緩存的維度

syntax:proxy_cache_key string;
default: proxy_cache_key $scheme(協議)$proxy_host$request_uri;
context: server.location;

例子

image

6、如何清理指定緩存

  • 方式1、rm -rf 緩存目錄內容
  • 方式2、第三方擴展模塊ngx_cache_purge

7、如何讓部分頁面不緩存

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

例子

location / {
    proxy_no_cache $cookie_nocache $arg_nocache $arg_comment;
    proxy_no_cache $http_pragma $http_authorization;
}

image

8、大文件分片請求

syntax:slice size;
default: slice 0;
context: http,server,location;

image

大文件分片請求

優勢:每個子請求收到的數據都會形成一個獨立文件,一個請求斷了,其他請求不受影響

缺點:當文件很大或者slice很小的時候,可能會導致文件描述符耗盡等情況

動靜分離

說明

將靜態請求和動態請求分離,分離資源,減少不必要的請求消耗,減少請求延時

例子

root /opt/app/code

location ~ \.jsp$ {
    proxy_pass http://java_api;
    index index.html index.html;
} 

location ~\.(jpg|png|gif)$ {
    expires 1h;
    gzip on;
} 

location / {
    index index.html index.html;
}

rewrite重寫

實現url重寫以及重定向

場景

  • URL訪問跳轉,支持開發設計,頁面跳轉,兼容性支持,展示效果等
  • SEO優化
  • 維護 后台維護、流量轉發等
  • 安全

配置語法

syntax:rewrite regex(正則) replacement [flag];
default: ;
context: server,location;

例子

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

flag

參數 說明
last 停止rewrite檢測
break 停止rewrite檢測
redirect 返回302臨時重定向,地址欄會顯示跳轉后的地址
permanent 返回301永久重定向,地址欄會顯示跳轉后的地址

rewrite規則優先級

  • 執行server的rewrite指令
  • 執行location匹配
  • 執行選定的location中的rewrie

高級模塊

  • 制定並允許檢查請求的鏈接的真實性以及保護資源免被受經授權的訪問
  • 限制鏈接生效周期

配置語法

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

原理

image
image

例子

server {
    listen 80;
    server_name localhost;
    root /opt/app/code;
    
    location / {
        #取得校驗參數
        secure_link $arg_md5,$arg_expires;
        #把過期時間 uri  password md5之后跟傳入的md5做校驗
        secure_link_md5 "$sercure_link_expires$uri password"
        
        if ($secur_link = "") {
            return 403;
        }
        if ($secure_link = "0") {
            return 410
        }
    }
}

geoip_module模塊

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

安裝

yum install nginx-module-geoip

使用場景

  • 區別國內外HTTP訪問規則
  • 區別國內部城市地域HTTP訪問區別

例子

image

HTTPS

https優化

  • 激活keepalive長連接

  • ssl session緩存

image

Nginx與lua開發

  • lua及基礎語法
  • nginx與lua環境
    場景:用nginx結合lua實現代碼的灰度發布

優勢

充分的結合nginx的並發處理epoll優勢和lua的輕量實現簡單的功能並且高比發的場景

安裝

yum install lua

運行

[root@VM_0_4_centos ~]# lua
Lua 5.1.4  Copyright (C) 1994-2008 Lua.org, PUC-Rio
> print("heollw")
heollw
>
# lua ./test.lua
heollw

nginx+lua環境

  1. luaJIT
  2. ngx_devel_kit和lua-nginx-module
  3. 重新編輯nginx

nginx調用lua模塊指令

nginx的可插拔模塊化加載執行,共11個處理階段

過程 說明
set_by_lua 設置nginx變量,可以實現復雜的賦值邏輯
set_by_lua_file
access_by_lua 請求訪問階段處理,用於訪問控制
access_by_lua_file
content_by_lua 內容處理器嗎,接受請求處理並輸出響應
content_by_lua_file

nginx lua api

參數 說明
ngx.var nginx變量
ngx.req.get_headers 獲取請求頭
ngx.req.get_uri_args 獲取uri請求參數
ngx.rediect 重定向
ngx.print 輸出響應內容體
ngx.say 通ngx.print,但是會最后輸出一個換行符
ngx.header 輸出響應頭

...

灰度發布

就是一部分用戶可以訪問,可以通過cookies或者ip等信息來區分

比如:

image

例子

image

lua邏輯

image

nginx常見問題

1. 相同server_name多個虛擬主機優先級訪問

server {
    listen 80;
    server_name testserver1 chenjinxinlove.com;
    location {
        
    }
}
server {
    listen 80;
    server_name testserver2 chenjinxinlove.com;
    location {
        
    }
}

默認使用先讀取的配置文件

2. location匹配優先級

  • = 進行普通字符精致匹配,也就是完成匹配
  • ^~ 表示普通字符匹配,使用前綴匹配
  • ~ ~* 表示執行一個正則匹配()
  1. try_files使用

按順序檢查文件是否存在

location / {
    try_files $uri $uri/ /index.php
}

使用可以先到緩存中查找沒有在去動態語言

4. nginx的alias和root區別

location /request_path/imgge/ {
    root /local_path/image
}

// 訪問的url
http:///www.chenjinxinlove/request_path/image/cat.png

// 實際路徑
/local_path/image/request_path/image/cat.png


location /request_path/imgge/ {
    alias /local_path/image
}

// 訪問的url
http:///www.chenjinxinlove/request_path/image/cat.png

// 實際路徑
/local_path/image/cat.png

5. 用什么方法傳遞用戶的真實ip

ip
ip1-->ip2-->ip2

set x_real_ip = $remote_addr  在ip1代理中設置真實

$x_real_ip =Ip1  在nginx就可以拿到

6.其他

  1. Nginx: 413Request Entity Too Large

用戶上傳文件限制client_max_body_size

  1. 502 bad gatway

后端服務無響應

  1. 504 Gateway Time-out

后端服務執行超時

nginx性能優化

1. 性能優化考慮點

  1. 當前系統結構瓶頸
    觀察指標、壓力測試

  2. 了解業務模式
    接口業務類型、系統層次化結構

  3. 性能與安全

2. 壓測工具ab

安裝

yum install httpd-tools

使用

ab -n 2000 -c 2 http://127.0.0.1
-n 總的請求數
-c 並發數
-k 是否開啟長連接

qps 每秒請求的次數

quest per second

[root@VM_0_4_centos ~]# ab -n 2000 -c 3 http://www.baidu.com/
This is ApacheBench, Version 2.3 <$Revision: 1430300 $>
Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/
Licensed to The Apache Software Foundation, http://www.apache.org/

Benchmarking www.baidu.com (be patient)
Completed 200 requests

Server Software:        BWS/1.1
Server Hostname:        www.baidu.com
Server Port:            80

Document Path:          /
Document Length:        118146 bytes

Concurrency Level:      3
Time taken for tests:   19.050 seconds
Complete requests:      324
Failed requests:        321
   (Connect: 0, Receive: 0, Length: 321, Exceptions: 0)
Write errors:           0
Total transferred:      38715469 bytes
HTML transferred:       38406497 bytes
Requests per second:    17.01 [#/sec] (mean)
Time per request:       176.389 [ms] (mean)
Time per request:       58.796 [ms] (mean, across all concurrent requests)
Transfer rate:          1984.68 [Kbytes/sec] received

Connection Times (ms)
              min  mean[+/-sd] median   max
Connect:        4    4   0.4      4      10
Processing:    14  170 205.9    186    3054
Waiting:        5   66  52.4     76     265
Total:         18  174 205.9    190    3058

Percentage of the requests served within a certain time (ms)
  50%    190
  66%    255
  75%    303
  80%    305
  90%    310
  95%    312
  98%    314
  99%    317
 100%   3058 (longest request)

3. 系統與nginx性能優化

  1. 網絡
  2. 系統
  3. 服務
  4. 程序
  5. 數據庫、底層服務
文件句柄

linux一起都是文件,文件句柄就是一個索引

設置方式

系統全局性修改、用戶局部修改、進程局部性修改

vim /etc/security/limits.conf

*就是所有的用戶

root               soft   nofile          10000
root               hard   nofile          20000
*                  soft   nofile          10000
*                  hard   nofile          20000

針對進程可以在nginx的配置文件中修改

worker_rlimit_nofile 20000
cpu親和和其他的常優化

把進程通常不會再處理器之間頻繁遷移進程遷移的頻率小,減少性能損耗

cat /proc/cpuinfo   記錄了cpu的信息
再nginx配置文件

# 根據cpu的核數做相應的配置,比如是16核
worker_processes 16;
# 把cpu全列出來
worker_cpu_affinity 00000000000000001 00000000000000010 ...;
# auto也可以
worker_cpu_affinity auto;

events {
    use epoll;
    # 默認就是1024個,可以調高
    worker_connections 10240;
}
http {
    # 統一設置成utf-8
    charset utf-8;
    # 日志可以關閉一些不用的
    access_log off;
    
    #Core module
    sendfile on;
    tcp_nopush on;
    tcp_nodeny on;
    keepalive_timeout 65;
    
    #Gzip module
    gzip on;
    # 兼容ie6
    gzip_disable "MSIE [1-6]\.";
    gzip_http_version 1.1;
}

安全

  • 常見的惡意行為
  • 常見的應用層攻擊手段
  • nginx防攻擊策略
  • 場景:nginx + lua的安全waf防火牆

1. 常見的惡意行為

  1. 爬蟲行為和惡意抓取、資源盜用
  2. 基礎防盜鏈功能-目的不讓惡意用戶能輕易的爬取網站對外數據
  3. secure_link_module - 對數據安全性提高加密驗證和失效性,適合核心重要的數據
  4. access_module -對后台。部分用戶服務的數據提供IP防控

常見的攻擊手段

后台密碼撞庫-通過猜測密碼字典不斷對后台系統登錄性嘗試,獲取后台登錄密碼

  • 后台登錄密碼復雜度
  • access_module - 對后台提供IP防控
  • 預警機制

文件上傳漏洞-利用一些可以上傳的接口將惡意代碼植入到服務器中在通過url去訪問以執行代碼

sql注入-利用未過濾/未審核用戶輸入的攻擊方法,讓應用運行本不應該運行對的SQL代碼

nginx+lua防火牆

image

比較好的實現

http://github.com/loveshell/ngx_lua_waf

分類

靜態
代理
動靜分類

image

設計評估

硬件 cpu 內存 硬盤(日志)

系統 用戶權限、日志目錄存放

關聯服務 LVS 、keepalive、syslog、Fastcgi

  • 合理配置
  • 了解原理
  • 關注日志


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM