一、Nginx簡介
Nginx ("engine x") 是一個高性能且輕量級的 HTTP 和 反向代理 服務器,同時也是一個 IMAP/POP3/SMTP 服務器。其特點是佔有內存少,併發能力強。我國使用nginx網站用戶有:百度、新浪、網易、騰訊等。
二、詳解Nginx主配置文件(nginx.conf)
user nobody nobody;#運行用戶與組 worker_processes 6;#啓動進程,通常設置與CPU數相同 worder_cpu_affinity4; #明確指定使用哪些CPU 如使用1、3核心: 1000 0010 worker_rlimit_nofile51200; #設置最大系統連接數 worker_priority 1; #指定調用CPU優先級;取值範圍(-20~20) #error_loglogs/error.log; #error_loglogs/error.log notice; #錯誤日誌及日誌級別;日誌級別有:(debug|info|notice|warn|error|crit|alert|emerg) #error_loglogs/error.log info; #pidlogs/nginx.pid; #PID文件路徑 lock_filelogs/nginx.lock; #鎖文件路徑 events { #事件模塊 use epoll; #指定事件驅動模型;(kqueue|rtsig|epoll|select|poll|eventport) worker_connections51200; #定義連接數限制;當超過1024時,須使用"ulimit -n"來解除系統連接限制 } http { #設置HTTP服務器模塊 include mime.types;#設置MIME類型 default_typeapplication/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_loglogs/access.log main; #設置訪問日誌及日誌格式 sendfile on; #指定Nginx是否調用sedfile函數 #autoindex on; #開啓索引功能,適合下載服務器,默認關閉 #tcp_nopush on; #防止網絡阻塞 #tcp_nodelay on; #防止網絡阻塞 #keepalive_timeout0; keepalive_timeout65; #連接超時時間,單位秒 server_names_hash_bucket_size128; #服務器名字Hash表大小 large_client_header_buffers4 32k; #設定請求緩存大小 client_header_buffer_size2k; #客戶端請求頭部緩衝區大小 client_body_buffer_size512k; #客戶端請求主休緩衝區大小 client_header_timeout60; #客戶端請求頭部超時時間 client_max_body_size8M; #設置通過Nginx上傳的文件大小 proxy_connect_timeout20; #代理連接超時時間 proxy_send_timeout60; #代理髮送超時時間 proxy_read_timeout20; #代理接收超時時間 proxy_buffer_size16k; #代理服務器保存用戶頭信息的緩衝區大小 proxy_buffers 464k; #存放後臺服務器緩衝區數量與大小 proxy_busy_buffers_size128k; #高負荷下緩衝大小 proxy_temp_file_write_size128k; #設置緩存文件夾大小 proxy_temp_path/usr/cache_one; #設置緩存文件夾位置 ######指定緩衝區的路徑、存儲方式及大小 proxy_cache_path/usr/proxy_cache_path levels=1:2 keys_zone=cache_one:200m inactive=1dmax_size=30g; gzip on; #開啓Gzip壓縮功能 gzip_min_length 1k;#最小壓縮文件大小 gzip_buffers 4 16k;#壓縮緩存區 gzip_http_version1.1; #壓縮版本 gzip_proxied off; #在代理中是否啓用壓縮功能 gzip_comp_level 5;#壓縮級別;默認爲1,取值範圍(1-9) ######壓縮文件類型 gzip_typestext/plain application/x-javascript text/css application/xmlapplication/javascript; gzip_vary on; upstream allen { #定義負載均衡配置,必須定義在"server"之外 ip_hash; #基於客戶端IP地址完成請求的分發,可以實現同一個客戶端的請求發送到同一臺服務器;有三種調度算法:輪詢(round-robin)、ip哈希(ip_hash)和最少連接(least_conn) server 172.16.14.2weight=1;#定義一個後端服務器;weight:權重 max_fails:最大失敗連接次數,失敗連接超時時間由fail_timeout設置 fail_timeout:等待請求目標服務器發送響應時長 backup:所有服務器都故障時才啓用此服務器 down:手動記錄此服務器不在做任何處理請求 server 172.16.14.3weight=1; } server { #定義一個虛擬主機,可以定義多個 listen 80; #監聽端口 server_namewww.allen.com; #定義主機名稱 #charset koi8-r; #設置字符集 #access_loglogs/host.access.log main; location / { #可以定義多個,也可以嵌套 root /web; #設置網站文件存放目錄 index index.phpindex.html index.htm; #設置默認訪問主頁 } location /status { stub_status on; #開啓Nginx狀態監測 access_log off; #關閉日誌訪問 } location ~ \.php$ {#定義以".php"結尾的文件 root /web; #定義php服務器網站存放目錄 fastcgi_pass172.16.14.2:9000; #定義fastcgi服務器地址及端口 fastcgi_indexindex.php; #定義默認訪問主頁 fastcgi_paramSCRIPT_FILENAME /scripts$fastcgi_script_name; includefastcgi_params; #定義fastcgi訪問文件 } #location ~.*\.(gif|jep|jpeg|png|bmp|swf|js|css|js|)$ { # proxy_cachecache_one; #設置緩存區 # proxy_cache_valid200 304 12h; #設置緩存時間 # proxy_cache_valid301 302 1m; # proxy_cache_validany 1m; # proxy_set_headerHost $host; #設置發送到代理服務器請求頭部添加額外信息 # proxy_set_headerX-Real-IP $remote_addr; # proxy_set_headerX-Forwarded-For $proxy_add_x_forwarded_for; # proxy_passhttp://allen; #} #location / { # if($request_method == “PUT”) { #如果客戶請求動作爲"PUT"就轉到定義的地址 # proxy_passhttp://www.allen.com:8080; # } # if ($request_uri~ "\.(jpg|gif|jpeg|png)$") { #如果客戶端請求"uri"有已經定義的文件結尾的文件就轉到定義好的地址然後跳出 # proxy_passhttp://p_w_picpathservers; # break; # } #if($http_user_agent ~ MSIE) { #如果客戶端請求使用的瀏覽器是IE,不管請求地址是什麼都轉到"/msie/"下面並跳出 #rewrite ^(.*)$/msie/$1 break; 註釋: ·last - 完成重寫指令,之後搜索相應的URI或location。 ·break - 完成重寫指令。 ·redirect - 返回302臨時重定向,如果替換字段用http://開頭則被使用。 ·permanent - 返回301永久重定向 #} #} #error_page 404 /404.html; # redirect servererror pages to the static page /50x.html # error_page 500 502503 504 /50x.html; #定義錯誤返回頁面 location =/50x.html { root html; } # proxy the PHPscripts to Apache listening on 127.0.0.1:80 # #location ~ \.php${ # proxy_pass http://127.0.0.1;#定義以".php"結尾的全部轉到指定的地址 #} # pass the PHPscripts to FastCGI server listening on 127.0.0.1:9000 # # deny access to.htaccess files, if Apache's document root # concurs withnginx's one # #location ~ /\.ht { # deny all; #} } # another virtual hostusing mix of IP-, name-, and port-based configuration # #server { # listen 8000; # listensomename:8080; # server_namesomename alias another.alias; # location / { # root html; # index index.htmlindex.htm; # } #} # HTTPS server # #server { #定義一個HTTPS服務器 # listen 443; # server_namelocalhost; # ssl on; # ssl_certificatecert.pem; #私鑰文件 #ssl_certificate_key cert.key; #頒發的證書 #ssl_session_timeout 5m; #會話超時時間 # ssl_protocolsSSLv2 SSLv3 TLSv1; #SSL協議版本 # ssl_ciphersHIGH:!aNULL:!MD5; #ssl_prefer_server_ciphers on; # location / { # root html; # index index.htmlindex.htm; # } #} }
三、if語句
語法:if (condition) { ... } 默認值:none 使用字段:server, location 判斷一個條件,如果條件成立,則後面的大括號內的語句將執行,相關配置從上級繼承。 可以在判斷語句中指定下列值: ·一個變量的名稱;不成立的值爲:空字符傳""或者一些用“0”開始的字符串。 ·一個使用=或者!=運算符的比較語句。 ·使用符號~*和~模式匹配的正則表達式。
四、URL重寫模塊(Rewrite)
~爲區分大小寫的匹配。 ~*不區分大小寫的匹配(allen匹配Allen)。 !~和!~*意爲“不匹配的”。 使用-f和!-f檢查一個文件是否存在。 使用-d和!-d檢查一個目錄是否存在。 使用-e和!-e檢查一個文件,目錄或者軟鏈接是否存在。 使用-x和!-x檢查一個文件是否爲可執行文件。 正則表達式的一部分可以用圓括號,方便之後按照順序用$1-$9來引用。
配置實例:
if ($http_cookie~* "id=([^;] +)(?:;|$)" ) { set $id $1; } if ($request_method= POST ) { return 405; } if (!-f$request_filename) { break; proxy_passhttp://127.0.0.1; } if ($slow){ limit_rate10k; } if ($invalid_referer){ return 403; } if ($args^~ post=140){ rewrite^ http://example.com/ permanent; }
五、Nginx負載均衡配置實例
兩臺WEB服務器就使用"Apahce"來實現,這裏使用rpm包安裝方式;然後提供一個測試頁面
1、編譯安裝Nginx
安裝Nginx依賴環境 [root@nginx~]# yum -y groupinstall "Development tools" "Server PlatformDevelopment" [root@nginx~]# yum -y install pcre-devel 添加Nginx運行用戶 [root@nginx~]# useradd -r nginx [root@nginx~]# tar xf nginx-1.4.2.tar.gz [root@nginx~]# cd nginx-1.4.2 編譯安裝Nginx [[email protected]]# ./configure \ > --prefix=/usr \ #Nginx安裝目錄 > --sbin-path=/usr/sbin/nginx \ #nginx執行程序安裝路徑 > --conf-path=/etc/nginx/nginx.conf \ #Nginx主配置文件存放路徑 > --error-log-path=/var/log/nginx/error.log \ #日誌文件存放路徑 > --http-log-path=/var/log/nginx/access.log \ > --pid-path=/var/run/nginx/nginx.pid \ #PID文件存放路徑 > --lock-path=/var/lock/nginx.lock\ #鎖文件存放路徑 > --user=nginx\ #指定運行Nginx用戶 > --group=nginx\ #指定運行Nginx組 > --with-http_ssl_module\ #開啓SSL加密模塊 > --with-http_flv_module\ #支持flv流媒體模塊 > --with-http_stub_status_module\ #開啓狀態檢測模塊 > --with-http_gzip_static_module\ #開啓gzip靜態壓縮模塊 > --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/ \ #fcgi緩存目錄 > --http-uwsgi-temp-path=/var/tmp/nginx/uwsgi \ #uwsgi緩存目錄 > --http-scgi-temp-path=/var/tmp/nginx/scgi \ #scgi緩存目錄 > --with-pcre #啓動正則表達式 [[email protected]]# make && make install
2、爲Nginx提供Sysv服務腳本
#!/bin/sh #nginx - this script starts and stops the nginx daemon #chkconfig: - 85 15 #description: Nginx is an HTTP(S) server, HTTP(S) reverse \ # proxy and IMAP/POP3 proxy server #processname: nginx #config: /etc/nginx/nginx.conf #config: /etc/sysconfig/nginx #pidfile: /var/run/nginx.pid #Source function library. . /etc/rc.d/init.d/functions #Source networking configuration. . /etc/sysconfig/network #Check that networking is up. [ "$NETWORKING" = "no" ] && exit 0 nginx="/usr/sbin/nginx" prog=$(basename $nginx) NGINX_CONF_FILE="/etc/nginx/nginx.conf" [-f /etc/sysconfig/nginx ] && . /etc/sysconfig/nginx lockfile=/var/lock/subsys/nginx make_dirs(){ #make required directories user=`nginx-V 2>&1 | grep "configure arguments:" | sed 's/[^*]*--user=\([^ ]*\).*/\1/g' -` options=`$nginx-V 2>&1 | grep 'configure arguments:'` for opt in $options; do if [ `echo $opt | grep '.*-temp-path'`]; then value=`echo $opt | cut -d "=" -f 2` if [ ! -d "$value" ]; then #echo "creating" $value mkdir -p $value && chown -R $user $value fi fi done } start(){ [-x $nginx ] || exit 5 [-f $NGINX_CONF_FILE ] || exit 6 make_dirs echo -n $"Starting $prog: " daemon$nginx -c $NGINX_CONF_FILE retval=$? echo [$retval -eq 0 ] && touch $lockfile return $retval } stop(){ echo -n $"Stopping $prog: " killproc$prog -QUIT retval=$? echo [$retval -eq 0 ] && rm -f $lockfile return $retval } restart(){ configtest|| return $? stop sleep 1 start } reload(){ configtest|| return $? echo -n $"Reloading $prog: " killproc$nginx -HUP RETVAL=$? echo } force_reload(){ restart } configtest(){ $nginx-t -c $NGINX_CONF_FILE } rh_status(){ status$prog } rh_status_q(){ rh_status>/dev/null 2>&1 } case "$1" in start) rh_status_q&& exit 0 $1 ;; stop) rh_status_q|| exit 0 $1 ;; restart|configtest) $1 ;; reload) rh_status_q|| exit 7 $1 ;; force-reload) force_reload ;; status) rh_status ;; condrestart|try-restart) rh_status_q|| exit 0 ;; *) echo $"Usage: $0{start|stop|status|restart|condrestart|try-restart|reload|force-reload|configtest}" exit 2 esac
3、將Nginx加入到系統服務並啓動
[root@nginx~]# chmod +x /etc/rc.d/init.d/nginx [root@nginx~]# chkconfig --add nginx [root@nginx~]# service nginx start 正在啓動 nginx: [確定]
4、查看Nginx進程並訪問測試
[root@nginx~]# ps aux|grep nginx root 2557 0.0 0.2 44444 816 ? Ss 15:20 0:00 nginx: master process /usr/sbin/nginx -c /etc/nginx/nginx.conf nginx 2558 0.7 0.5 44852 1508 ? S 15:20 0:00 nginx: worker process
5、在WEB1服務器上安裝Httpd並啓動
[root@web1~]# yum -y install httpd [root@web1~]# service httpd start
6、爲WEB1服務器提供一個測試頁面並做訪問測試
[root@web1~]# echo 'web1 172.16.14.2' > /var/www/html/index.html
7、在WEB2服務器上面安裝Httpd並啓動
[root@web2~]# yum -y install httpd [root@web2~]# service httpd start
8、爲WEB2服務器提供一個測試頁面並做訪問測試
[root@web2~]# echo 'web1 172.16.14.3' > /var/www/html/index.html
配置Nginx實現負載均衡
1、修改主配置文件
#user nobody; worker_processes 4; #error_log logs/error.log; #error_log logs/error.log notice; #error_log logs/error.log info; worker_rlimit_nofile 51200; #pid logs/nginx.pid; events { use epoll; 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; server_names_hash_bucket_size 128; client_header_buffer_size 32k; large_client_header_buffers 4 32k; client_max_body_size 300m; client_body_buffer_size 512k; sendfile on; tcp_nopush on; keepalive_timeout 65; proxy_connect_timeout 20; proxy_send_timeout 60; proxy_read_timeout 20; proxy_buffer_size 16k; proxy_buffers 4 64k; proxy_busy_buffers_size 128k; proxy_temp_file_write_size 128k; gzip on; gzip_min_length 1k; gzip_buffers 4 16k; gzip_http_version 1.1; gzip_comp_level 5; gzip_vary on; upstream allen { server 172.16.14.2; server 172.16.14.3; } server { listen 80; server_name localhost; #charset koi8-r; #access_log logs/host.access.log main; location / { proxy_pass http://allen; index index.html index.htm; } # redirect server error pages to thestatic page /50x.html # error_page 500 502 503 504 /50x.html; location = /50x.html { root html; } } }
2、測試Nginx主配置文件語法,並重新加載
[root@nginx ~]#nginx -t nginx: theconfiguration file /etc/nginx/nginx.conf syntax is ok nginx:configuration file /etc/nginx/nginx.conf test is successful [root@nginx ~]#service nginx reload
3、訪問Nginx主機驗證是否實現負載均衡,需要多刷新幾次
web1訪問成功
web2訪問成功
Nginx實現後端健康狀態檢測
1、修改Nginx主配置文件如下
upstream allen { server 172.16.14.2 backup; server 172.16.14.3 max_fails=3 fail_timeout=2s; } 此處要注意: backup:作爲備份服務器,當所有服務器都停止了服務,此時backup備份機會啓用 max_fails:請求超時後,最大檢測後端服務器次數 fail_timeout:超時時間;默認爲10s
2、重新加載配置文件
[root@nginx ~]#service nginx reload
3、測試訪問到的頁面是否爲WEB2服務器的
4、此時,停止WEB2服務器的Httpd服務,驗證請求的內容是否爲WEB1服務器內容
[root@web2 ~]#service httpd stop Stoppinghttpd: [ OK ]
5、把WEB2服務器Httpd服務啓動,此時請求到的內容爲WEB2服務器。
給Nginx添加第三方模塊實現過載保護
1、下載擴展補丁包,解壓並打補丁
下載地址:https://codeload.github.com/alibaba/nginx-http-sysguard/zip/master
[root@nginx ~]#unzip nginx-http-sysguard-master.zip [root@nginx ~]# cdnginx-1.4.2 [[email protected]]# patch -p1 <../nginx-http-sysguard-master/nginx_sysguard_1.3.9.patch
2、重新編譯安裝Nginx
[[email protected]]# ./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.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 \ > --add-module=/root/nginx-http-sysguard-master/ [[email protected]]# make && make install
3、 修改Nginx配置文件添加過載保護;這裏說明下爲了測試方便,把CPU負載調的比較低
[email protected]]# cd /etc/nginx/ [root@nginx nginx]#vim nginx.conf 在"server"模塊中添加如下內容 sysguard on; #開啓過載保護功能 sysguard_load load=0.3action=/loadlimit; #cpu負載超過0.3就保護,"action"過載保護動作 #sysguard_mem swapratio=20% action=/swaplimit;#交換分區過載保 #sysguard_mem free=100Maction=/freelimit; #內存過載保護 location /loadlimit { return 503; #系統過載返回503 } 注意:由於新添加了功能需要重啓Nginx服務 [root@nginx nginx]#service nginx restart
4、 安裝"htop"工具,監測負載
[root@nginx ~]# yum-y install htop [root@nginx ~]#htop
5、在另一臺主機使用apache自帶的壓力測試工具ab做壓測;在壓測前先訪問一下是否正常。
[root@web1 ~]# ab-n 50000 -c 1000 http://172.16.14.1/index.html
6、查看Nginx服務器的負載狀況
7、 測試訪問Nginx服務器是否能正常訪問