1. 程式人生 > 實用技巧 >Nginx基本使用方法及各模組基本功能

Nginx基本使用方法及各模組基本功能

一、Nginx介紹

Nginx是由俄羅斯軟體工程師Igor Sysoev開發的一個高效能的HTTP和反向代理伺服器,具備IMAP/POP3和SMTP伺服器功能,Nginx最大的特點是對高併發的支援和高效的負載均衡,在高併發的需求場景下,是Apache伺服器不錯的替代品。目前,包括新浪、騰訊等知名網站都已使用Nginx作為Web應用伺服器。下面我簡單介紹一下:

nginx是一個高效能的Web和反向代理伺服器,它具有很多非常優越的特性;

作為Web伺服器;相比較與Apache,Nginx使用更少的資源,支援更多的併發連線,體現更高的效率,這點使Nginx尤為受到虛擬主機提供商的歡迎,能夠支援高達50000個併發的連線數的響應。

作為負載均衡伺服器器:Nginx既可以在內部直接支援Rails和PHP,也可以支援作為HTTP代理伺服器對外驚醒服務,Nginx用C語言編寫,不論是系統資源開銷還是CPU使用效率都比Perlbal要好的多。

作為郵件代理伺服器,Nginx同時也是一個非常優秀的郵件代理伺服器(最早開發這個產品的目的之一也是作為郵件代理伺服器),Last.fm描述了成功並且美妙的使用經驗。

Nginx安裝非常簡單,配置檔案非常簡介(還能夠支援perl語法),Bugs非常少的伺服器:Nginx啟動特別容易,並且幾乎可以做到7*24不間斷執行,即使執行數月也不需要重新啟動。還能夠在不間斷服務的情況下進行軟體版本平滑升級。

二、軟體獲得及幫助文件

官方地址:http://nginx.org

下載穩定版本:http://nginx.org/download/nginx-1.8.0.tar.gz

幫助文件:http://nginx.org/en/docs

編譯引數說明:http://nginx.org/en/docs/configure.html

三、Nginx的功能

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657581、Nginx的特性模組化設計、較好的擴充套件性高可靠性:一個master啟動一或多個worker,每個worker響應多個請求低記憶體消耗:10000個keepalive連線在Nginx中僅消耗2.5MB記憶體(官方資料)支援熱部署:不停機更新配置檔案、更新日誌檔案、更新伺服器程式版本2、Nginx的基本功能靜態web資源伺服器,能夠快取開啟的檔案描述符支援http/imap/pop3/smtp的反向代理;支援快取、負載均衡支援fastcgi(fpm)模組化,非DSO機制,支援過濾器zip壓縮,SSI以及影象大小調整支援SSL3、Nginx的擴充套件功能基於名稱和IP的虛擬主機支援keepalive的保持機制支援平滑升級定製訪問日誌,支援使用日誌快取區提高日誌儲存效能支援urlrewrite支援路徑別名(root或alias指定)支援基於IP以及使用者的訪問控制支援傳輸速率限制,併發限制4、Nginx的基本架構一個master程序,生成一個或者多個worker程序,每個worker響應多個請求事件驅動:epoll,kqueue,poll,select,rtsignals支援sendfile,sendfile64支援AIO支援mmap5、Nginx模組型別Nginxcoremodule:nginx的核心模組StandardHTTPmodules:nginx的標準模組OptionalHTTPmodules:nginx的可選模組Mailmodules:nginx的郵件模組3rdpartymodules:nginx的第三方模組6、Nginx程序詳解主程序主要完成如下工作:讀取並驗正配置資訊;建立、繫結及關閉套接字;啟動、終止及維護worker程序的個數;無須中止服務而重新配置工作特性;控制非中斷式程序升級,啟用新的二進位制程式並在需要時回滾至老版本;重新開啟日誌檔案,實現日誌滾動;編譯嵌入式perl指令碼;worker程序主要完成的任務包括:接收、傳入並處理來自客戶端的連線;提供反向代理及過濾功能;nginx任何能完成的其它任務;cacheloader程序主要完成的任務包括:檢查快取儲存中的快取物件;使用快取元資料建立記憶體資料庫;cachemanager程序的主要任務:快取的失效及過期檢驗;

四、Nginx安裝配置

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192201、安裝依賴包(CentOS6.7)[[email protected]soft]#yum-ygroupinstall"Developmenttools,Serverplatformdevelopment,Desktopplatformdevelopment"[[email protected]soft]#yum-yinstallpcre-developenssl-devel2、編譯安裝Nginx[[email protected]soft]#tarxfnginx-1.8.0.tar.gz[[email protected]soft]#cdnginx-1.8.0[[email protected]nginx-1.8.0]#groupadd-rnginx[[email protected]nginx-1.8.0]#useradd-gnginx-s/sbin/nologin-Mnginx[[email protected]nginx-1.8.0]#./configure\--prefix=/usr/local/nginx\--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.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[[email protected]nginx-1.8.0]#make&&makeinstall##注意:編譯後有些資料夾不會自動建立[[email protected]nginx-1.8.0]#mkdir-pv/var/tmp/nginx/{client,proxy,fcgi,uwsgi,scgi}mkdir:createddirectory`/var/tmp/nginx'mkdir:createddirectory`/var/tmp/nginx/client'mkdir:createddirectory`/var/tmp/nginx/proxy'mkdir:createddirectory`/var/tmp/nginx/fcgi'mkdir:createddirectory`/var/tmp/nginx/uwsgi'mkdir:createddirectory`/var/tmp/nginx/scgi'這裡的二進位制檔案是直接指定在PATH環境變數裡面的,所有可以直接使用,不用匯出:配置vim,使其編輯nginx配置檔案時語法著色,預設沒有[[email protected]nginx-1.8.0]#cd[[email protected]~]#mkdir.vim[[email protected]~]#cp-ra/u01/soft/nginx-1.8.0/contrib/vim/*.vim[[email protected]~]#ls.vimftdetectindentsyntax編寫啟動指令碼:[[email protected]~]#vim/etc/rc.d/init.d/nginx#!/bin/sh##nginx-thisscriptstartsandstopsthenginxdaemin##chkconfig:-8515#description:NginxisanHTTP(S)server,HTTP(S)reverse\#proxyandIMAP/POP3proxyserver#processname:nginx#config:/etc/nginx/nginx.conf#pidfile:/var/run/nginx.pid#Sourcefunctionlibrary../etc/rc.d/init.d/functions#Sourcenetworkingconfiguration../etc/sysconfig/network#Checkthatnetworkingisup.["$NETWORKING"="no"]&&exit0nginx="/usr/sbin/nginx"prog=$(basename$nginx)NGINX_CONF_FILE="/etc/nginx/nginx.conf"lockfile=/var/lock/subsys/nginxstart(){[-x$nginx]||exit5[-f$NGINX_CONF_FILE]||exit6echo-n$"Starting$prog:"daemon$nginx-c$NGINX_CONF_FILEretval=$?echo[$retval-eq0]&&touch$lockfilereturn$retval}stop(){echo-n$"Stopping$prog:"killproc$prog-QUITretval=$?echo[$retval-eq0]&&rm-f$lockfilereturn$retval}restart(){configtest||return$?stopstart}reload(){configtest||return$?echo-n$"Reloading$prog:"killproc$nginx-HUPRETVAL=$?echo}force_reload(){restart}configtest(){$nginx-t-c$NGINX_CONF_FILE}rh_status(){status$prog}rh_status_q(){rh_status>/dev/null2>&1}case"$1"instart)rh_status_q&&exit0$1;;stop)rh_status_q||exit0$1;;restart|configtest)$1;;reload)rh_status_q||exit7$1;;force-reload)force_reload;;status)rh_status;;condrestart|try-restart)rh_status_q||exit0;;*)echo$"Usage:$0{start|stop|status|restart|condrestart|try-restart|reload|force-reload|configtest}"exit2esac[[email protected]~]#chmod+x/etc/rc.d/init.d/nginx#新增可執行許可權[[email protected]~]#chkconfig--addnginx#新增到服務列表[[email protected]~]#chkconfignginxon#設定開機自啟動[[email protected]~]#servicenginxstart#啟動nginxStartingnginx:[OK][[email protected]~]#ss-tnl#檢視是否監聽80埠[[email protected]~]#ss-tnlStateRecv-QSend-QLocalAddress:PortPeerAddress:PortLISTEN0128*:80*:*LISTEN0128:::22:::*LISTEN0128*:22*:*##檢視頁面[[email protected]~]#curlhttp://localhost<!DOCTYPEhtml><html><head><title>Welcometonginx!</title><style>body{width:35em;margin:0auto;font-family:Tahoma,Verdana,Arial,sans-serif;}</style></head><body><h1>Welcometonginx!</h1><p>Ifyouseethispage,thenginxwebserverissuccessfullyinstalledandworking.Furtherconfigurationisrequired.</p><p>Foronlinedocumentationandsupportpleasereferto<ahref="http://nginx.org/">nginx.org</a>.<br/>Commercialsupportisavailableat<ahref="http://nginx.com/">nginx.com</a>.</p><p><em>Thankyouforusingnginx.</em></p></body></html>#######################編譯安裝已經完成。配置檔案介紹主要有兩部分:分別是main:主體部分http{}:虛擬主機配置部分配置指令主要以分號結尾;配置語法:directivevalue1[value2....]支援使用的變數模組內建的變數自定義變數:setvar_namevalue主配置段的指令類別:用於除錯和定位問題:(1)daemon[on|off]:是否以守護程序的方式啟動nginx;(2)master_press[on|off]:是否以master/worker模型來執行nginx;(3)error_log/path/to/error_loglevel:指明錯誤日誌檔案級別,處於除錯目的,可以使用debug級別,但次級別只有在編譯nginx時使用了--with-debug選項才有效;正常執行必備的配置:(1)userUSERNAME[GROUPNAME]:指定執行worker的使用者和使用者組;例如usernginxnginx(2)pid/path/to/nginx.pid:指定pid檔案(3)worker_rlimit_nofile#:指定一個worker程序能夠開啟的最大檔案控制代碼數(4)worker_rlimit_sigpending#:指定每個使用者能夠發往worker訊號的數量優化效能相關的配置:(1)worker_processes#:worker程序的個數,通常是cpu核心數減1(2)worker_cpu_affinitycpuumask:繫結worker程序至指定的CPU上(3)timer-resolutiont:時間解析度,在x86伺服器上可以不用配置(4)worker_priorityNICE:調整nice值(-20,19);nice值越大,越優先分配cpu事件相關的配置;(1)accept_mutex[on|off]:內部調動使用者請求至各worker時的負載均衡鎖;啟用時表示能夠讓多個worker輪流的、序列化的響應請求(2)lock_file/path/to/lock_file:指定鎖檔案(3)accept_mutex_delay#ms:取得負載均衡鎖的時間(4)use[epoll|poll|select|rgsig]:定義使用的事件模型,建議讓nginx自動選擇(5)worker_connections#:每個worker程序所能夠響應的最大併發請求數

五、Nginx的一些基本功能實現

12345678910111213141516171819202122232425262728293031321、基於使用者認證:(1)、修改配置檔案server{listen80;server_namelocalhost;#charsetkoi8-r;#access_loglogs/host.access.logmain;location/{roothtml;indexindex.htmlindex.htm;auth_basic"www.bjwf125.com";auth_basic_user_file/www/html/.passwd;}}(2)、建立文件根目錄以及使用httpd-tools中的htpasswd工具建立使用者[[email protected]~]#mkdir-pv/www/htmlmkdir:createddirectory`/www'mkdir:createddirectory`/www/html'[[email protected]~]#echo"Welcometobjwf125">/www/html/index.html[[email protected]~]#yum-yinstallhttpd-tools[[email protected]~]#htpasswd-c-m/www/html/.passwdcentos#建立centos使用者Newpassword:#輸入密碼Re-typenewpassword:#再次輸入Addingpasswordforusercentos(3)、重新載入配置檔案[[email protected]~]#nginx-t#檢查Nginx語法nginx:theconfigurationfile/etc/nginx/nginx.confsyntaxisoknginx:configurationfile/etc/nginx/nginx.conftestissuccessful[[email protected]~]#servicenginxreload#重新載入

wKioL1aVrVfgNYf4AAGSN0NIzVQ440.png

123456789101112131415161718192021222324252627282930313233343536373839404142432、基於IP認證server{listen80;server_namelocalhost;#charsetkoi8-r;#access_loglogs/host.access.logmain;location/{roothtml;indexindex.htmlindex.htm;deny192.168.9.0/24;allowall;}}3、基於gzip壓縮server{listen80;server_namelocalhost;#charsetkoi8-r;#access_loglogs/host.access.logmain;location/{root/www/html;indexindex.htmlindex.htm;gzipon;gzip_http_version1.0;gzip_min_length1000;gzip_proxiedexpiredno-cacheno-storeprivateauth;gzip_typestext/plainapplication/xmltext/cssapplication/x-javascripttext/xmlapplication/xml+rsstext/javascriptapplication/javascriptapplication/json;gzip_disablemsie6safari;}}[[email protected]~]#nginx-t[[email protected]~]#servicenginxreload[[email protected]~]#cp/etc/rc.d/rc.sysinit/www/html/zip.html[[email protected]~]#ll/www/html/zip.html-h-rwxr-xr-x1rootroot20KJan1310:01/www/html/zip.html

wKiom1aVs12CRESrAAElOeZcn4I017.png

1234567891011121314151617184、定製響應頭部server{listen80;server_namelocalhost;#charsetkoi8-r;#access_loglogs/host.access.logmain;location/{root/www/html;indexindex.htmlindex.htm;expires24h;add_headerbjwf125mymail;}}[[email protected]~]#nginx-t[[email protected]~]#servicenginxreload

wKioL1aVtYbQ5ibvAAFWdcXTzZ8041.png

12345678910111213141516171819202122232425262728295、URL重定向語法格式:rewritegrgexreplacement[flages]flageslast:一旦被當前規則匹配並重寫後立即停止檢查其他後續的rewrite的規則,而後通過重寫後的規則重寫發起請求;bleak:一旦被當前規則匹配並重寫後立即停止後續的其他rewrite的規則,而後由nginx進行後續操作;redirect:返回302臨時重定向permanent:返回301永久重定向例如:[[email protected]~]#vim/etc/nginx/nginx.confserver{listen80;server_namelocalhost;#charsetkoi8-r;#access_loglogs/host.access.logmain;location/{root/www/html;indexindex.htmlindex.htm;rewrite^/admin/(.*)$/web/$1;}}[[email protected]~]#mkdir-pv/www/html/{admin,web}[[email protected]~]#echo"mail.bjwf125.com">/www/html/web/index.html[[email protected]~]#nginx-t[[email protected]~]#servicenginxreload

wKiom1aVuBrSz58EAACIOfL4jvY427.png

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869706、虛擬主機[[email protected]nginx]#vim/etc/nginx/nginx.conf#註釋掉http{}段中的預定義server{}段中的所有內容;在檔案末尾}前一行新增一條:includeconf.d/nginx-vhost.conf;#方便後面定義,根據個人習慣而已,也可以直接在/etc/nginx/nginx.conf中配置[[email protected]nginx]#vim/etc/nginx/conf.d/nginx-vhost.confserver{listen80;server_namewww.a.com;location/{root/www/html/a;indexindex.htmlindex.htm;}}server{listen80;server_namewww.b.com;location/{root/www/html/b;indexindex.htmlindex.htm;}}[[email protected]nginx]#mkdir/www/html/{a,b}-pvmkdir:createddirectory`/www/html/a'mkdir:createddirectory`/www/html/b'[[email protected]nginx]#echo"www.a.com">/www/html/a/index.html[[email protected]nginx]#echo"www.b.com">/www/html/b/index.html[[email protected]nginx]#vim/etc/hosts192.168.9.9www.a.com192.168.9.9www.b.com[[email protected]nginx]#servicenginxreload[[email protected]nginx]#curlhttp://www.a.comwww.a.com[[email protected]nginx]#curlhttp://www.b.comwww.b.com###虛擬主機最簡單的方式已經配置完成,但是虛擬主機裡面還有很多引數。7、防盜鏈(1)、定義合規的引用valid_referersnone|blocked|server_names|string...;(2)、拒絕不合規的引用if($invalidreferer){rewrite^/http://www.b.com/403.html;}##具體示例如下:[[email protected]conf.d]#vimnginx-vhost.confserver{listen80;server_namewww.b.com;location/{root/www/html/b;indexindex.htmlindex.htm;valid_referersnoneblockedwww.b.com*.b.com;if($invalid_referer){rewrite^/http://www.b.com/403.html;}}}[[email protected]conf.d]#vim/www/html/a/index.htmlwww.a.com<imgsrc="http://www.b.com/p_w_picpaths/1.jpg">#在a.com中引用[[email protected]conf.d]#vim/www/html/b/index.htmlwww.b.com<imgsrc="http://www.b.com/p_w_picpaths/1.jpg">#b.com自己引用

測試結果:

wKioL1aVwwTyoLWTAABho2r65aA758.pngwKioL1aVwxiiPePJAAGFvZDq19c001.png

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465668、Nginx的反向代理Nginx可以通過proxy模組實現反向代理功能,在作為web反向代理伺服器時,Nginx複製接收客戶端請求,並能夠根據URL、客戶端引數或者其它的處理邏輯將使用者請求排程至上游伺服器上(upstreamserver)。Nginx在實現反向代理功能時最重要的指令為proxy_pass,它能夠將location中定義的某URI代理至指定的上游伺服器(組)上。如下面的示例中,location的URI將被替換為上游伺服器上的newURI。###例如:[[email protected]conf.d]#vimnginx-vhost.confserver{listen80;server_namewww.a.com;add_headerX-Via$server_addr;location/{root/www/html/a;indexindex.htmlindex.htm;}location=/node2{proxy_passhttp://192.168.9.11/;}}##上游伺服器必須要配置相應服務及頁面[[email protected]conf.d]#servicenginxreload[[email protected]conf.d]#curlwww.a.com<imgsrc="http://www.b.net/p_w_picpaths/1.jpg">[[email protected]conf.d]#curlhttp://www.a.com/node1node1.bjwf125.com(1)、快取:Nginx作為反向代理時,能夠將上游伺服器的響應快取至本地,並在後續的客戶端請求同樣的內容時直接從本地構造響應報文。具體引數如下:proxy_cachezone|off:定義一個用於快取的共享記憶體區域,其可被多個地方呼叫;proxy_cache_path:定義一個儲存快取響應報文的目錄,及一個儲存快取物件的鍵及響應元資料的共享記憶體區域(keys_zone=name:size),其可選引數有:levels:每級子目錄名稱的長度,有效值為1或2,每級之間使用冒號分隔,最多為3級;inactive:非活動快取項從快取中剔除之前的最大快取時長;max_size:快取空間大小的上限,當需要快取的物件超出此空間限定時,快取管理器將基於LRU演算法對其進行清理;loader_files:快取載入器(cache_loader)的每次工作過程使用為多少個檔案載入元資料;loader_sleep:快取載入器的每次迭代工作之後的睡眠時長;loader_threashold:快取載入器的最大睡眠時長;proxy_cache_valid[code...]time:用於為不同的響應設定不同時長的有效快取時長,例如:proxy_cache_valid20030210m;proxy_cache_methods[GETHEADPOST]:為哪些請求方法啟用快取功能;proxy_cache_bypassstring:設定在哪種情形下,nginx將不從快取中取資料。示例:#vim/etc/nginx/nginx.confhttp{includemime.types;default_typeapplication/octet-stream;proxy_cache_path/data/nginx/cachelevels=1:2keys_zone=STATIC:10minactive=24hmax_size=1g;server{listen80;server_namenode1;add_headerX-Via$server_addr;location/{root/www/html/b;indexindex.htmlindex.htm;proxy_passhttp://192.168.9.11;proxy_set_headerHost$host;proxy_cacheSTATIC;proxy_cache_valid2001d;proxy_cache_valid30130210m;proxy_cache_validany1m;proxy_cache_use_staleerrortimeoutinvalid_headerupdatinghttp_500http_502http_503http_504;}}}[[email protected]nginx]#mkdir-pv/data/nginx/cache[[email protected]nginx]#nginx-t[[email protected]nginx]#servicenginxreload


快取前請求時間


wKiom1aV7-SAyWEQAAGrwmlONBg169.png


快取後請求時間


wKiom1aV8AOBELMsAAGrp1jsVVY909.png

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152####主要檔案太小,效果不是太明顯,有強迫症的同學可以自己測試。##此時可以檢視快取目錄是否有檔案生成[[email protected]~]#ll/data/nginx/cache/drwx------3nginxnginx4096Jan1314:321(2)、負載均衡:Nginx可以利用自身的upstream模組實現,upstream模組的負載均衡演算法主要有三種,輪調(round-robin)、ip雜湊(ip_hash)和最少連線(least_conn)三種。upstream模組常用的指令有:ip_hash:基於客戶端IP地址完成請求的分發,它可以保證來自於同一個客戶端的請求始終被轉發至同一個upstream伺服器;keepalive:每個worker程序為傳送到upstream伺服器的連線所快取的個數;least_conn:最少連線排程演算法;server:定義一個upstream伺服器的地址,還可包括一系列可選引數,如;weight:權重;max_fails:最大失敗的連線次數,失敗連線的超時時長由fail_timeout指定;fail_timeout:等待請求的目錄伺服器傳送響應的時長;backup:用於fallback的目的,所有服務均故障時才啟動此伺服器;down:手動標記其不再處理任何請求;示例:#vim/etc/nginx/nginx.confhttp{upstreamweb{server192.168.9.11:80max_fails=3fail_timeout=10s;server192.168.9.13:80max_fails=3fail_timeout=10s;server127.0.0.1:8080backup;}server{listen80;server_namewww.c.net;add_headerX-Via$server_addr;location/{root/www/html/b;indexindex.htmlindex.htm;proxy_passhttp://web;}}server{listen8080;server_name127.0.0.1;location/{root/www/html/b;indexindex.htmlindex.htm;}}[[email protected]~]#curlhttp://www.c.net192.168.9.11[[email protected]~]#curlhttp://www.c.net192.168.9.13##停掉上游兩臺伺服器後:[[email protected]~]#curlhttp://www.c.netSorry#####Nginx的基本功能基本完成

The end

有關Nginx的基本配置及一般用法就寫到這裡了,第一次寫Nginx的部落格,寫的比較亂,比較雜,敬請諒解,有什麼不對的地方,麻煩朋友們告訴我。以上為個人學習整理,如有錯漏,大神勿噴。。。。。


本文出自 “張強” 部落格,請務必保留此出處http://79076431.blog.51cto.com/8977042/1734595


轉載於:https://blog.51cto.com/lucifer119/1734848