nginx火的緣由
一個線程內程序交替執行 select、poll、epoll select: 1)可以監視文件描述符的數量存在最大限制 2)線性掃描效率低 epoll: linux內核2.6之後對select進行的優化 1)每當FD就緒採用系統的回調函數將FD放入、效率高 2)最大鏈接數無限制
1)內置功能模塊少 2)代碼模塊化 之因此輕量級,就是因位內置少,可是官方有不少插件
worker進程和cpu綁定,減小cpu切換的cache miss
爲何nginx處理靜態文件有優點呢? 由於當請求到來時,通常是 file -----> kernol space ---> user space | socket <----kernol space<-----user space 而是直接 file -----> kernol space | socket <----kernol space
Mainline version 開發版
Stable version 穩定版
Legacy version 歷史版本
方式一:php
wget http://nginx.org/download/nginx-1.14.1.tar.gz tar zxvf nginx-1.14.1.tar.gz cd nginx-1.14.1 yum -y install zlib zlib-devel yum -y install gcc gcc-c++ autoconf pcre pcre-devel make automake yum -y install wget httpd-tools vim ./configure --prefix=/usr/local/nginx make && make install
方式二(官方推薦):html
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
操做系統centos7.2
yum ------->安裝的rpm包 rpm -ql nginx 已經安裝的服務的一些配置文件的所在目錄
路徑 | 類型 | 做用 |
/usr/lib/systemd/system/nginx-debug.service | 配置文件 | 用於配置出系統前端 守護進程管理器node 管理方式linux |
/usr/lib/systemd/system/nginx.service | ||
/etc/sysconfig/nginx | ||
/etc/sysconfig/nginx-debug | ||
/etc/nginx/nginx.conf | nginx的主配置文件nginx |
|
/etc/nginx/conf.d/default.conf | ||
/etc/nginx/fastcgi_params | php專用 | |
/etc/nginx/uwsgi_params | ||
/etc/nginx/scgi_params | ||
/etc/logrotate.d/nginx | nginx日誌輪轉 | |
/etc/nginx/mime.types | 設置Content-type與擴展名的關係 | |
/etc/nginx/koi-utf /etc/nginx/modulesredis /usr/lib64/nginx |
nginx -v 版本 nginx -V 編譯時的一些信息
# 安裝目的目錄或路徑
--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
--ock-path=/var/run/nginx.lock
# 安裝編譯的參數 (執行對應模塊式,Nginx所保留的臨時性文件)
--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 設定Nginx進程啓動的用戶和組用戶
--group=nginx
--with-cc-opt=parameters 設置額外的參數將被添加到CFLAGS變量
(存入一些編譯過程當中優化的參數;好比說咱們nginx使用的select,在這裏可配置最大FD數)
--with-ld-opt=parameters 設置附加的參數,連接系統庫 例如pcre
yum install curl curl http://www.baidu.com 拿到返回的字符串
user 設置nginx服務的系統使用用戶
worker_processes 工做進程數
error_log nginx錯誤日誌
pid nginx服務啓動時候pid
events worker_connections 每一個進程容許最大鏈接數
最大65535,通常10000
use 工做進程數
nginx 日誌格式參數 :能夠分爲3種 1)http請求變量 arg_PARAMETER、http_HEADER、sent_http_HEADER 在配置時需, - 變成_ 大寫變小寫 nginx -t -c /etc/nginx/nginx.conf 檢查配置文件是否正確, 路徑檢查 2)內置變量 由於比較多,看官網 http://nginx.org/en/docs/http/ngx_http_core_module.html#var_status 3)自定義變量
nginx的信號量: # kill -INT master的PID TERM,INT 緊急殺掉,輕易不要用 nginx -s stop QUIT 優雅的關閉,請求完畢後殺 nginx -s quit HUP 重讀配置文件,開啓新的worker,殺死舊的worker nginx -s reload USE1 重讀日誌,在日誌按月、日分割時有用 nginx -s reopen 實際在linux裏一個文件是一個inode;名字只是表象罷了; 當日志備份時mv **.log **.log.bat不行,由於此文件一直在被nginx打開,就算改了名字依然指向對應的內存空間;就算刪了也無論用
(文件系統的特殊性,一直向對應的inode寫數據,文件名無關) --->備份1 mv **.log **.log.bat ;2 kill -USE1 進程pid USE2 平滑的升級, WINCH 和USE2配合使用,優雅的關閉舊的進程 nginx -t 測試配置是否正確
日誌的定時切割 須要shell #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; date -s '2018-11-16 08:45:30' clock -w ------->寫shell腳本runlof.sh #!/bin/shell LOGPATH=/usr/local/nginx/logs/access.log BASEPATH=/usr/local/nginx/bak/$(date -d yesterday +"%Y%m") mkdir -p $BASEPATH bak=$BASEPATH/$(date -d yesterday +"%d%H%M").access.log mv $LOGPATH $bak touch $LOGPATH kill -USE1 `cat /usr/local/nginx/logs/nginx.pid` # 分 時 日 月 周 # 建立定時任務 crontab -e * * */1 * * sh /usr/local/nginx/runlog.sh
1)官方shell
源碼包內包含的 以及不包含但官方支持的模塊
2)第三方
--with-http_stub_status_module 展現nginx當前鏈接的一個狀態 syntax;stub_status; Context;server,location location /xxx{ stub_status; }
--with-http_random_index_module 主目錄中選擇一個隨機主頁 但不包括以。開頭的隱藏文件
Syntax: random_index on|off;
Default: random_index off;
Context: location
location /{
root /opt/ap/code;
random_index on;
}
--with-http_sub_module s--->c HTTP內容替換 ()
Syntax : sub_filter string replacement; Default : -- Context :http,server,location
location / {
root /opt/app/code;
index index.html index.htm
sub_filter '<a>imooc</a>' '<a>IMOOC</a>'
}
Syntax :sub_filter_last_modified on|off;
Default :sub_filter_last_modified off;
Context :http,server,location
# last_modified 校驗服務端返回數據較上一次是否發生變換;請求頭;緩存;
Syntax :sub_filter_once on|off; Default :sub_filter_once on; # 只匹配第一個/指定的內容都進行一次匹配 Context:http,server,location
limit_conn_module 連接頻率限制 limit_req_module 請求頻率限制 區別:鏈接 請求上不一樣 http1.0 TCP不能複用 http1.1 順序性tcp複用 http2.0 多路複用tcp複用 http請求創建在一次tcp鏈接基礎上 一次tcp請求至少產生一次http請求 Systax :limit_conn_zone key zone=name:size; Default :-- Context :http Systax : limit_conn zone number; Default :-- Context : http,server,location
Systax : limit_req_zone key zone=name:size rate=rate;
Default :-- Context : http
Systax : limit_req zone key zone=name [burst=number] [nodelay];
Default :-- Context : http,server,location
limit_conn_zone $binanry_remote_addr zone=conn_zone:1m; limit_req_zone $binary_remote_addr zone=req_zone:1m rate=1r/s;
limit_conn conn_zone 1;
limit_req zone=req_zome burst=3 nodelay; 超出限制的請求,會有3個請求,在下一秒執行
limit_req
精度的限制,鏈接限制-請求限制,屢次請求能夠創建在一次的鏈接基礎上
yum install htppd -y
ab -n 40 -c 20 http://192.162.22.150/1.html
基於ip的訪問控制 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;
allow 222.128.189.0/24;
deny all;
index index.html,index.htm;
}
方式一: http_x_forwarded_for = Client IP, Proxy(1) IP,Proxy(2) IP,..
侷限; x_forwarded_for 是一個協議要求的,但不是強制的;代理廠商並必定會照作,還存在被修改的可能性,
方式二;結合geo模塊
方式3、經過http自定義變量傳遞
再頭信息裏自定義一個咱們規定的http的變量,聯繫上一層的設備,把客戶端remote_addr的信息攜帶到咱們規定變量裏,
一層一層的攜帶到咱們後端,既能避免x_forwarded_for 被改寫,也能在後端準確的讀到ip
基於用戶的信任登陸 http_auth_basic_module
侷限性:當用戶使用代理訪問,remote_addr顯示的是代理的IP,並非真正的客戶所使用的IP
Syntax :auth_basic string |off; # string 即表示了開啓,也能夠顯示在前端 Default :auth_basic off; Context :http,server,location,limit_except
Syntax :auth_basic_user_file file; # 路徑 Default :-- Context :http,server,location,limit_except
# comment name1:password1 name2:password2:comment name3:password3
提供了htpasswd加密方式 通常有 yum install httpd-tools -y
htpasswd -c ./auth_conf zhangsan
new password: *****
zhangsan:$apr1$pIH0Y1zJ$yUzMeK2su7LihULhqcPta1c
相同密碼--->加密後不一樣
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.htm;
}
再訪問時,會提示要輸入用戶名和密碼
侷限性:
解決方案;
處理靜態文件的優點講解
Syntax : sendfile on |off; Default : sendfile off; Context : http,server,location,if in location 引讀: --with-file-aio異步文件讀取 目前效果不是特別好
Syntax :tcp_nopush on|off;
Default :tcp_nopush off;
Context :http,server,location
資源打包發送(),對報文的處理,提升了網絡的傳輸速度,(推薦大文件)
做用:sendfile 開啓的狀況下,提升網絡包的傳輸效率
Syntax :tcp_nodelay on|off;
Default :tcp_nodelay on;
Context :http,server,location
數據包不等待,實時性發送
做用: 在keep-alive鏈接下,提升網絡包的傳輸實時性
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
Syntax : gzip_http_version 1.0|1.1; Default : gzip_http_version 1.1; Context :http,server,location
http_gzip_static_module 預讀gzip功能
Syntax : gzip_static on;
手動壓縮 gzip ./test.img 會生成一個test.img.gz,原文件不存在
瀏覽器緩存 校驗過時機制
nginx相關設置
Syntax : expires [modified] time; Default : expires off; Context : http,server,location,if in location
狀態碼304,數據從緩存中獲取的。
nginx的csrf
Syntax : add_header name value [always]; Default : -- Context : http,server,location,if inlocation
add_header Access-Control-Allow-Origin http://www.jesonc.com;
add_header Access-Control-Allow-Methods GET,POST,PUT,DELETE,OPTIONS;
防盜鏈;
但願規矩的用戶,合法的用戶訪問,
大部分沒用的用戶來訪問,勢必會對系統性能和請求形成了必定的損耗
目的:防止資源被盜用
首要方式:區別哪些請求是非正常的用戶請求
基於http_refer防盜鏈配置模塊
Syntax :valid_referers none | blocked |server_names|string;
Default :--
Context :server,location
location ~.*\.(jpg|gif|png)${
valid_referers none blocked 192.168.0.1 ~/google\./;
if ($valid_referer) {
retutrn 403;
}
root /opt/app/code/images;
}
正向代理 與反向代理的區別:
區別在於代理的對象不同
正向代理 代理的對象是 客戶端
反向代理 代理的對象是 服務端
Syntax : proxy_pass URL; Default : -- Context :location,if in location,limit_except
http://localhost:8000/uri/ https://192.168.1.1:8000/uri/ http://unix:/tmp/backend.socket:/uri/;
正向代理
resolver 8.8.8.8; # 谷歌的dns服務器 locaion / { proxy_pass http://$http_host$request_uri; }
反向代理 : 經過80端口去訪問其餘端口
一個server表明一個虛擬主機
server{ listen 80; server_name localhoost www.shuoiliu.com; location / { proxy_pass http://127.0.0.1:8000; } }
緩衝區 Syntax :proxy_buffering on|off; Default :proxy_buffering on; Context :http,server,location 擴展 :proxy_buffer_size、proxy_buffers、proxy_busy_buffers_size
跳轉重定向 Syntax :proxy_redirect default; proxy_redorect off;proxy_redirect redirect replacement; Default :proxy_redirect default; Context :http,server,location
頭信息
Syntax :proxy_set_header field value;
Default :proxy_set_header Hosy $proxy_host;
proxy_set_header Connection close;
Context :http,server,location
擴展:proxy_hide_header、proxy_set_body
超時 Syntax :proxy_connection_timeout time; Default :proxy_connection_timeout 60s; Context :http,server,location 擴展:proxy_read_timeout、proxy_send_timeout
處理的時間
企業經常使用
resolver 8.8.8.8; # 谷歌的dns服務器 locaion / { proxy_pass http://$http_host$request_uri; proxy_redirect default; proxy_set_header Host $http_host; proxy_set_header X-Readl-Ip $remoter_addr; proxy_connection_timeout 30; proxy_read_timeout 60; proxy_write_timeout 60; proxy_buffer_size 32k; proxy_buffering on; # 能夠減小頻繁的IO proxy_buffers 4 128k; # 內存 proxy_busy_buffers_size 256k; # 內存 proxy_max_temp_file_size 256k; # 硬盤 }
緩衝區臨時文件存放的地點看編譯過程的信息,裏面有
隨着企業業務的增加,以及帶來的客戶的海量的請求,給服務端形成了海量的併發,使響應不能及時。
---> 擴容後端服務,前端須要一個負載均衡來均分請求,以提高總體的吞吐率。
單點的方式訪問,若是一個點蕩吊了,總體也就蕩吊了。
可是有了負載均衡,一個掛掉了,其餘的點也能夠正常使用,剔除就能夠了。
默認的負載均衡的算法: 是設置計數器,輪流請求N臺服務器. 能夠安裝第3方模式,來利用uri作hash等等. 如http://wiki.nginx.org/NginxHttpUpstreamConsistentHash 這個模塊就是用一致性hash來請求後端結節,而且其算法,與PHP中的memcache模塊的一致性hash算法,兼容. 安裝該模塊後: Nginx.conf中 upstream memserver { consistent_hash $request_uri; server localhost:11211 weight=3 max_fails=3 fail_timeout=10s; server localhost:11212 weight=1 max_fails=3 fail_timeout=10s; }
按照範圍分類,GSLB,SLB
全局負載均衡(範圍比較大),
nginx就是一個SLB,每每企業不會大規模部署GSLB而是用到雲的服務以及第三方的總體設備。 按照osi能夠分爲 四層負載均衡 和七層負載均衡 物理 鏈路 網絡 傳輸(tcp/ip) 會話 表示 應用 四層已經支持TCP/ip控制,只須要對客戶端的請求進行tcp/ip協議的包轉發,性能非能快,只須要對底層的應用處理 七層能夠完成不少應用方面的協議的請求;(http信息改寫,安全應用規則的控制,轉發 ,重寫)nginx就是
upstream server 服務單元s 默認依次輪訓, (一致性哈希)
Syntax :upstream name {...} Default :-- Context :http
不對外提供8002端口的服務
iptables -I INPUT -p tcp --dport 8002 -j DROP
upstream backend { server backend1.example.com weight=5; # 權重 server backend2.example.com:8080; server unix;/tmp/backend3; server backup1.example.com:8080 backup; # 備份節點 server backup2.example.com:8080 backup; }
down 當前的server暫時不參與負載均衡
backup 預留的備份服務器,默認不分發,只有當其餘忙不過來時,幫忙分發,ip_hash 不支持
max_fails 容許請求失敗的次數 fail_timeout 通過max_fails失敗後,服務暫停的時間,默認10秒
max_conns 限制最大的接受的鏈接數
基於host分發 基於開發語言的分發 基於請求頭的分發 基於源IP的分發

輪詢 按時間順序桌椅分配到不一樣的後端服務器
加權輪詢 weight值越大,分配到的訪問概率越高
least_conn 最少連接數,那個機器鏈接少就分發
ip_hash 每一個請求訪問IP的hash結果分配,這樣來自同一個ip的 固定訪問一個後端服務器 remote_addr(沒法基於同一臺服務器 代理)
第三方
url_hash 按照訪問的url的hash結果來分配請求,是每一個url丁香島同一個後端服務器
hash 關鍵數值 hash自定義的key
內置,http_header,自定義
fair 第三方;安後端服務器的響應時間來分配請求,響應式夾斷的優先分配
Syntax :hash key [consistent]; #$request_url; Default :-- Context :upstream this directive appeared in version 1.7.2
減小後端壓力,儘可能讓全部請求都能在前端得到數據,處理掉。
服務端緩存;redis,memcache
代理緩存; nginx
客戶端緩存:
proxy_cache 配置語法 必須 Syntax :proxy_cache_path path [levels=levels(1:2)][use_temp_path=on|off] keys_zone=name:size [incative=time] [max_size=size(10g)] [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 :http
Syntax :proxy_cache zone |off; Default :proxy_cache off; Context :http,server,location
緩存過時週期 Syntax :proxy_cache_valid [code ...] time; # 狀態碼 Default :-- Context :http,server,location
緩存維度 Syntax :proxy_cache_key string; Default :proxy_cache_key $scheme$proxy_host$request_uri; # 協議主機url Context :http,server,location
部分頁面不緩存
Syntax :proxy_no_cache string ...;
Default :--
Context :server,http,location
if ($request_uri ~ ^/(url3|login|register|password\/reset){
set $cookie_nocache 1;
}
proxy_next_upstream
防止後端其中一臺服務器,出現問題,則跳過這一臺
如何清理指定緩存
官方沒有提供
用第三方擴展模塊 ngx_cache_purge (編譯\安裝)
清理全部緩存:
rm -rf /opt/app/cache/
大文件分片請求 Syntax :slice size; Default ;slice 0; Context :http,server,location 1.9之後出現
優點:每一個自請求收到的數據都會造成一個獨立文件,一個請求斷了,其餘請求不受影響
缺點:當文件很大或者slice很小的時候,可能會致使文件描述符耗盡的狀況
rewirte 實現url重寫以及重定向 應用場景 1) url 訪問跳轉,支持開發設計 頁面跳轉。兼容性支持。展現效果 2) SEO優化, 方便搜索引擎的錄入 3)維護 後臺維護。流量轉發 4)安全 將真實的頁面假裝
Syntax : rewrite regex replacement [flag]; Default : -- Context :server,location,if
flag
last 中止rewrite檢測
break 中止rewrite檢測
redirect 返回302臨時重定向,地址欄會顯示跳轉後的地址
permanent 返回301永久重定向,地址欄會顯示跳轉後的地址
rewrite ^ http://www.baidu.com$request_uri?;
rewrite ^(.*)$ /index$1.html break; # 內容重定向一次
last 與 break的區別:
break 找不到index$1文件會返回404
last 會從新訪問一次 只不過url變成了/index$1.html
rewrite ^/course-(\d+)-(\d+)-(\d+)\.html$ /course/$1/$2/course_$3.html break;if (!-f $request_filename){ rewrite ^/(.*)$ http://www.baidu.com/ redirect;}! 取反, -f 判斷路徑是否存在