Nginx----基礎篇
ngnix基本特性
nginx 常用的方式 web server web reverse proxy cacahe
輕量級更適合現代互聯網架構
基本功能
能夠實現服務靜態資源,能緩存打開的文件描述符,文件下次訪問時速度加快
反向代理服務器能實現緩存,負載均衡等功能
特性:
支持fastCGI
模塊化機制非DSO機制,支持多種過濾器例如:gzip,ssi和圖像大小調整
支持SSL
擴展功能
能實現基於名稱和IP做虛擬主機
支持keepalived
支持平滑配置文件更新和版本升級
支持訪問日誌定製,支持使用 日誌緩存以提高性能
支持url rewrite
支持路徑別名
支持基於ip及用戶的認證基於htpasswd實現
原生支持速率限制,併發數限制等
Nginx基本架構
一個master,生成一個或多個work每個work關聯所需的filter
基於事件驅動:kqueue ,epoll, /dev/poll
支持消息通知機制:select,poll,rt singnle
支持sendfile,sendfile64
支持文件的AIO(異步IO)
支持mmap:直接將硬盤空間分頁映射成內存空間
Ngnix的模塊:
核心模塊
標準http模塊 默認安裝的模塊
可選的http模塊 默認都是不安裝的
郵件模塊
第三方模塊
安裝配置
官方文檔站點:http://wiki.nginx.org/Main
編譯安裝和rpm epel源或官方下載安裝源
編譯環境準備
yum groupinstall “Development Tools” “Server Platform Development”
yum install pcre-devel
nginx的配置文件
main配置段
http配置段
mail配置段
配置參數需要以分號結尾 語法格式: 參數名 值1 [值2];
還支持使用變量:模塊的內置變量和用戶自定義變量: set var_name value
通常而言ngnix基本配置類別
用於調試,定位問題
正常運行的必備配置
優化性能的配置
事件類配置
Worker進程通常以普通用戶身份運行:nginx:nginx
首先添加用戶useradd -r ngnix ./configure \ --prefix=/usr \ --sbin-path=/usr/sbin/nginx \ --conf-path=/etc/nginx/nginx.conf \ --error-log-path=/var/log/nginx/error.log \ --http-log-path=/var/log/nginx/access.log \ --pid-path=/var/run/nginx/nginx.pid \ --lock-path=/var/lock/nginx/nginx.lock \ --user=nginx \ --group=nginx \ --with-http_ssl_module \ --with-http_flv_module \ --with-http_stub_status_module \ --with-http_gzip_static_module \ --http-client-body-temp-path=/var/tmp/nginx/client \ --http-proxy-temp-path=/var/tmp/nginx/proxy \ --http-fastcgi-temp-path=/var/tmp/nginx/fcgi \ --http-uwsgi-temp-path=/var/tmp/nginx/uwsgi \ --http-scgi-temp-path=/var/tmp/nginx/scgi \ --with-pcre Make && make install
啓動選項:
[root@localhost nginx-1.6.2]# nginx -h nginx version: nginx/1.6.2 Usage: nginx [-?hvVtq] [-s signal] [-c filename] [-p prefix] [-g directives] Options: -?,-h : this help -v : show version and exit -V : show version and configure options then exit -t : test configuration and exit -q ;suppress non-error messages during configuration testing -s signal : send signal to a master process: stop, quit, reopen, reload 可以實現平滑啓動 -p prefix : set prefix path (default: /usr/) -c filename : set configuration file (default: /etc/nginx/nginx.conf) -g directives : set global directives out of configuration file 配置文件語法檢測 [root@localhost nginx-1.6.2]# nginx -t nginx: the configuration file /etc/nginx/nginx.conf syntax is ok nginx: [emerg] mkdir() "/var/tmp/nginx/client" failed (2: No such file or directory) nginx: configuration file /etc/nginx/nginx.conf test failed 根據錯誤創建目錄 [root@localhost nginx-1.6.2]# mkdir -pv /var/tmp/nginx/client mkdir: created directory `/var/tmp/nginx' mkdir: created directory `/var/tmp/nginx/client' [root@localhost nginx-1.6.2]# nginx -t nginx: the configuration file /etc/nginx/nginx.conf syntax is ok nginx: configuration file /etc/nginx/nginx.conf test is successful 啓動nginx [root@localhost nginx-1.6.2]# nginx [root@localhost nginx-1.6.2]# ss -tnl | grep "80" LISTEN 0 128 *:80 *:* 查看啓動的nginx進程 [root@localhost nginx-1.6.2]# ps aux | grep "nginx" root 6331 0.0 0.2 44864 1140 ? Ss 11:03 0:00 nginx: master process nginx nginx 6332 0.0 0.3 45316 2000 ? S 11:03 0:00 nginx: worker process root 6347 0.0 0.1 103248 852 pts/0 S+ 11:06 0:00 grep nginx
正如上面所訴當前啓動了一個master和一個worker並且master以root執行 worker則以nginx用戶執行
默認打開配置文件沒有語法高亮顯示爲了支持語法高亮
http://www.vim.org/scripts/script.php?script_id=1886
install details |
Download nginx.vim to ~/.vim/syntax/, and then add this line to ~/.vim/filetype.vim: |
Nginx的配置
正常運行的必備配置
1,user usr_name [group_name] 也可編譯時指定
2,pid /path/pid_file 指定pid文件 也可在編譯時指定
3,worker_rlimit_nofile 指定一個worker所能打開的最大文件句柄數
4,worker_rlimit_sigpending 設定每個用戶能夠發往worker進程的信號數量
性能相關的配置
1,worker_processes worker進程的個數 一般來講此值等於cpu核心數減去1
2,worker_cpu_affinity cpu掩碼 cpu親緣性 儘量避免進程上下文切換
例如:worker_cpu_affinity 000001 000010 000100 001000 010000 100000 表示分別綁定在6顆cpu上
3,ssl_engine device 在存在ssl硬件加速器的服務器上使用指定的ssl硬件加速設備
4,timer_resolution 時間 單位爲ms 每次內核事件調用返回時,都會使用gettimeofday()來更新nginx緩存時鐘;早期時這個系統代價很大每次返回都調用會影響系統性能 所以此選項用於定義每隔多長時間纔會由gettimeofday()更新一次緩存時鐘:x86_64系統上,gettimeofday()代價很小不啓用也可以
5,worker_oriority nice值 -20--19之間的值
事件相關的配置
1,accept_mutex [on|off] 是否打開nginx上master調度worker的負載均衡鎖 此鎖能使多個worker進程輪流的,序列的與新的客戶端建立連接,而通常當一個worker進程負載達到其上限的7/8,master就儘可能不講請求調度至此woorker 默認是打開的
2,lock_file /path/lock_file
定義1鎖文件是哪個
3,accept_mutex_delay 初始值ms accept鎖模式中一個worker進程爲取得accept鎖的等待時間,如果某worker進程在否次試圖取得鎖時失敗,至少要等待定義的時長,默認500ms
4,multi_accept on|off 是否允許一次性的響應多個用戶請求 默認是off
5,use 事件模型[epoll|rtsig|select|poll] rtsig爲實時信號處理
定義使用的事件類型建議讓nginx自動選擇
6,worker_connections num 每個worker能夠響應的最大請求數
用於調試,定位問題:只調試nginx時使用
1,Daemon [on|off]
是否讓nginx運行於後臺,默認爲on調試時可以設置爲off,是的調試時信息輸出至控制檯
2,master_process [on|off]
是否以master/worker模式運行nginx 默認爲on 調試時設爲off以方便追蹤
3,error_log /path/err_log level
錯誤日誌文件及其級別;調試時可以使
用debug級別,但在編譯時必須使用--with-debug功能默認爲error級別
Nginx的http功能
必須使用虛擬主機來配置站點:每個虛擬主機使用一個server段 server { }
多個虛擬主機的共享配置或非虛擬主機選項必須配置在server段外
總體格式
http { Directive value; .......... Server { } Server { } ............. }
常用參數
server {} 定義一個虛擬主機:nginx支持使用基於主機名和IP的虛擬主機
1,Listen address [:port]
listen port
listen unix:socket
Listen Default_server:定義此server爲http中默認的server,如果所有的server中沒有任何一個listen 使用此參數那麼第一個server爲默認server
Rcvbuf=size:接收緩衝大小
Sndbuf=size:發送緩衝大小
Ssl: https server
2,server_name [name] 設定主機名 可跟多個主機名ngnix收到一個用戶請求時,會取出其首部的server的值,而後跟衆server比較
比較的方式
[1] 先做精確匹配 www.centod.com
[2] 左側通配符匹配 *.centod.com
[3]右側通配符匹配 www.*
[4]正則表達式匹配 ~^\.centod\.com$
3,server_name_hash_bucket_size 32|64|128 爲了快速查找主機查找,nginx使用hash表保存主機名
4,location [=|~|~*|^~] uri {.....}
Location @name {......}
作用:允許根據uri的需要來匹配指定的各location進行訪問配置 ,匹配到時就被location魁塊中的配置所處理
=:精確匹配
~:正則表達式模式匹配,匹配時區分大小寫
~*:正則表達式模式匹配,匹配時忽略大小寫
^~:只需前半部匹配即可,不檢查正則表達式
匹配優先級:字符字面量最精確匹配,正則表達式檢索(若多個匹配到被第一個匹配),按字符字面量
Location中使用的指令[文件路徑定義]
1,root path :設置web資源路徑:用於指定請求的根文檔路徑
location / {
root /www/htdocs
}
localtion ^~ /image {
root /web
}
若訪問http://www.baidu.com/則是訪問的文件在主機的/www/htdocs這個目錄下
若訪問http://www.baidu.com/image則訪問的文件在/web/image這個目錄的下的文件
2,alias path
只能用於location中,用於路徑別名
例如localtion ^~ /image {
alias /web
}
若訪問http://www.baidu.com/image則訪問的是/web下的文件
3,index .....file
定義默認主頁 可跟多個值從左至右匹配
4,error_page code ....... [=[response]] Uri
當對於某個請求返回錯誤時,如果匹配上error_page指令中設定的code,則跳至error_page指定的頁面
例如 error_page 404=200 /error.html
5,try_files path1 [path2......] uri;
依次尋找指定文件都沒有則到uri
網絡連接相關的設置
1,keepalived_timeout time; 設置保持連接的超時時間,默認時間是75s
2,keepalived_requests n; 在一次長連接上允許承載的最大請求數
3,keepalive_disable [msi6|safari|none] :對指定的瀏覽器禁止使用長連接因爲有些老的瀏覽器不支持長連接
4,tcp_nodelay on|off 對keepalived連接是否使用TCP_NODELAY選項 等待報文合併就叫delay 通常設置爲on否則用戶請求得到的應答有可能是找不到
5,client_header_timeout time 讀取http請求的首部的超時時間
6,client_bady_timeout time 讀取實體的超時時間 兩個默認都是60
7,send_timeout time 發送響應的超時時長
對客戶端請求的限制:
1,limit_except method ........{....} :除了指定的方法都可以使用
示例:limit_except GET {
Allow 172.16.0.0/16;
Deny all;
}
2,client_max_body_size SIZE;實體的最大值 常用於限定客戶端所能請求的最大實體值,根據請求首部的content_length來做檢測 上傳限制等 避免無用的傳輸
3,limit_rate speed;限制客戶端每秒傳輸的字節數,默認爲0,表示不限制 也可寫成40k
4,limit_rate_after time;nginx向客戶端發送響應的報文時,如果超出了此處指定的時長,則後續發送過程開始限速
文件操作的優化:
1,senfile on|off 是否啓用sendfi功能
2,aio on|off 是否啓用aio
3,open_file_cache max=n [inactive=time]|off 是否打開文件緩存功能
max:指定緩存條目的最大值 當滿了後將根據LRU算法進行置換 LRU最近最少使用算法
Inactive:若緩存在指定時長內沒有被訪問過則自動刪除 默認爲60s
緩存的信息包括:文件句柄 ,文件大小和上次修改的時間,已經打開的目錄結構,沒有找到或沒有訪問權限的信息也會緩存
4,open_file_cache_errors on|off 是否緩存文件找不到貨沒有權限的訪問等相關信息
5,open_file_cache_valid time;多長時間檢查一次緩存中的條目是否超出非活動時間,默認60s
6,open_file_cache_min_use num;在inactive指定的時長內被訪問此處指定的次數的,纔不會被刪除
對客戶端請求的特殊處理
1,ignore_invalid_heards on|off;是否忽略不合法的http首部 默認爲on off表示出現不合法的拒絕響應
2,log_not_found on|off;當用戶訪問的資源沒有找到是否將信息記錄到錯誤日誌中
3,resovler address; 指定nginx使用的dns服務器地址
4,resolver_timeout time;指定dns解析的超時時長 默認30s
5,server_tokens on|off 是否顯示錯誤頁面中的nginx的版本號
http核心模塊的內置變量
$uri : 當前請求的uri
$host:請求報文中的host首部,如果請求中沒有host首部,則以處理此請求的虛擬主機的主機名代替
$request_uri:請求的uri,帶完整參數
$hostname:nginx服務運行在的主機的主機名
$remote_addr:客戶端IP
$remote_port:客戶端port
$remote_user;使用用戶認證時客戶端用戶輸入的用戶名
$request_filename:用戶請求中的uri經過本地的root或alias轉換後的本地文件的文件路徑
$request_mothod:請求方法
$server_addr:服務器地址
$server_name:服務器名稱
$server_port:服務器端口
$server_protocol:服務器向客戶端發送的協議的版本
$scheme:在請求中使用的scheme ,如https://www.google.com/中的https
$http_HEARD:匹配請求報文中指定的HEARD,如$http_host請求報文中的host首部
$sent_http_HEARD:匹配響應報文中指定的HEARD
$document_root:當前請求映射到的root請求項
Nginx基礎應用
創建兩個虛擬主機
www.centod.com 主頁文件 /www/centod/index.html 內容爲www.centod.com
www.centoc.com 主頁文件 /www/centoc/index.html 內容爲www.centoc.com
並且設置管理員主頁爲/admin/index.html 內容爲 admin area
配置文件如下
worker_processes 1; events { worker_connections 1024; } http { include mime.types; default_type application/octet-stream; sendfile on; keepalive_timeout 65; server { listen 80; server_name www.centod.com; location / { root /www/centod; index index.html index.htm; } error_page 500 502 503 504 /50x.html; location = /50x.html { root html; } } server { listen 80; server_name www.centoc.com; root /www/centoc; location / { index index.html; } location /admin { auth_basic "This is home of Admin please go away"; auth_basic_user_file /etc/nginx/.htpasswd; index index.html } }
創建目錄及所需的文件
mkdir /www/{centod,centoc}/ -pv
[root@node2 nginx]# touch /www/{centod,centoc}/index.html
[root@node2 nginx]# vim /www/centod/index.html
[root@node2 nginx]# vim /www/centoc/index.html
[root@node2 nginx]# mkdir /www/centoc/admin
[root@node2 nginx]# vim /www/centoc/admin/index.html
創建認證文件
[root@node2 nginx]# htpasswd -m -c /etc/nginx/.htpasswd centoc
啓動nginx
客戶端修改host文件使之能夠解析兩個域名
172.16.101.200 www.centod.com
172.16.101.200 www.centoc.com
客戶端測試
防盜鏈需要兩條指令
1,定義符合的引用
Valid_referers none|blocked |server_names|string.....;
2,定義不符合的引用
If ($invalid_referer) {
Rewrite
}
If用法比較操作符 == ~ ~* !
If測試操作 -d -f -e -x
URL重寫
Rewrite regex replacement [flag]
查找regex[正則表達式]替換成replacement
Falg: 1,last:一旦停止被當前規則匹配並重寫後立即停止檢查後續的其他rewrire規則,而通過重寫後的規則重新發起請求
2,break:一旦停止被當前規則匹配並重寫後立即停止檢查後續的其他rewrire規則,而後繼續由nginx進行後續的操作
3,redirect:返回302臨時重定向
4,permanent:返回301永久重定向
示例:location /download/ {
rewrite ^(/download/.*)/media/(.*)\..*$ $1/media/$2.mp3 break;
}
會陷入死循環 nginx最多循環10次,然後返回500錯誤
爲了防止死循環,一般將rewrite寫在location中時都要使用break獲獎rewerite寫在if上下文中
rewrite_log on|off :是否將重寫工程寫在錯誤日誌中:默認爲notice級別 默認爲off 打開會影響性能
Return code:用於結束rewrite規則,併爲用戶返回狀態碼,可以使用的狀態碼有 204 400 402-406 500-504等
If用法
If (condition) { }
防盜鏈的實現與重寫
假設http://www.centoc.com/images/1.gpg不允許來自於其他站點引用則如下方法實現
首先創建使用到的資源
[root@node2 nginx]# mkdir /www/centoc/images 放入圖片1.jpg [root@node2 images]# mkdir /www/centoc/error [root@node2 images]# vim /www/centoc/error/index.html
在centoc虛擬主機中添加如下location
location ~*\.(jpg|gif|png|jpeg)$ { valid_referers none blocked www.centoc.com *.centoc.com ~\.baidu\.; if ($invalid_referer) { rewrite ^/ http://www.centoc.com/error/index.html last; } }
編輯centod主頁文件
<h1> www.centod.com </h1>
<img src="http://www.centoc.com/images/1.jpg"
編輯www.centoc.com/error/index.html
<h1> inter file please access http://www.centoc.com </h1>
重新載入nginx配置文件
實驗如下圖
www.centoc.com可正常訪問
點擊查看圖像會顯示我們定義好的資源
證明www.centod.com無法盜用www.centoc.com網站資源