歡迎您光臨本站 註冊首頁

Nginx 常見應用技術指南(Nginx Tips)

←手機掃碼閱讀     火星人 @ 2014-03-03 , reply:0

Nginx 常見應用技術指南(Nginx Tips)

Nginx 常見應用技術指南(Nginx Tips)


目錄:
一. Nginx基礎知識
二. Nginx安裝配置
三. Nginx Rewrite
四. Nginx Redirect
五. Nginx 目錄自動加斜線
六. Nginx 防盜鏈
七. Nginx expires
八. Nginx 訪問控制
九. Nginx Location
十. Nginx 日誌處理
十一.  Nginx Cache服務配置
十二.  Nginx 負載均衡
十三.  Nginx 優化
十四.  Nginx 相關參考文檔

   【前言】:
編寫此技術指南在於推廣普及NGINX在國內的使用,更方便的幫助大家了解和掌握NGINX的一些使用技巧。本指南很多技巧來自於網路在此對網路上願意分享的朋友們表示感謝和致意!歡迎大家和我一起豐富本技術指南並提出更好的建議!

一.Nginx 基礎知識
1.簡介
   Nginx ("engine x") 是一個高性能的 HTTP 和 反向代理 伺服器,也是一個 IMAP/POP3/SMTP 代理伺服器。 Nginx 是由 Igor Sysoev 為俄羅斯訪問量第二的 Rambler.ru 站點開發的,它已經在該站點運行超過兩年半了。Igor 將源代碼以類BSD許可證的形式發布。儘管還是測試版,但是,Nginx 已經因為它的穩定性、豐富的功能集、示例配置文件和低系統資源的消耗而聞名了。更多的請見官方wiki: http://wiki.codemongers.com/NginxChs

2.Nginx的優點
  nginx做為HTTP伺服器,有以下幾項基本特性:
  1.處理靜態文件,索引文件以及自動索引;打開文件描述符緩衝.
  2.無緩存的反向代理加速,簡單的負載均衡和容錯.

3.FastCGI,簡單的負載均衡和容錯.

4.模塊化的結構。包括gzipping, byte ranges, chunked responses, 以及 SSI-filter等filter。如果由FastCGI或其它代理伺服器處理單頁中存在的多個SSI,則這項處理可以并行運行,而不需要相互等待。

5.支持SSL 和 TLS SNI.
Nginx專為性能優化而開發,性能是其最重要的考量, 實現上非常注重效率 。它支持內核Poll模型,能經受高負載的考驗, 有報告表明能支持高達 50,000 個併發連接數。
Nginx具有很高的穩定性。其它HTTP伺服器,當遇到訪問的峰值,或者有人惡意發起慢速連接時,也很可能會導致伺服器物理內存耗盡頻繁交換,失去響應,只能重啟伺服器。例如當前apache一旦上到200個以上進程,web響應速度就明顯非常緩慢了。而Nginx採取了分階段資源分配技術,使得它的CPU與內存佔用率非常低。nginx官方表示保持10,000個沒有活動的連接,它只佔2.5M內存,所以類似DOS這樣的攻擊對nginx來說基本上是毫無用處的。就穩定性而言, nginx比lighthttpd更勝一籌。
Nginx支持熱部署。它的啟動特別容易, 並且幾乎可以做到7*24不間斷運行,即使運行數個月也不需要重新啟動。你還能夠在不間斷服務的情況下,對軟體版本進行進行升級。
Nginx採用master-slave模型, 能夠充分利用SMP的優勢,且能夠減少工作進程在磁碟I/O的阻塞延遲。當採用select()/poll()調用時,還可以限制每個進程的連接數。
Nginx代碼質量非常高,代碼很規範, 手法成熟, 模塊擴展也很容易。特別值得一提的是強大的Upstream與Filter鏈。 Upstream為諸如reverse proxy, 與其他伺服器通信模塊的編寫奠定了很好的基礎。而Filter鏈最酷的部分就是各個filter不必等待前一個filter執行完畢。它可以把前一個filter的輸出做為當前filter的輸入,這有點像Unix的管線。這意味著,一個模塊可以開始壓縮從後端伺服器發送過來的請求,且可以在模塊接收完後端伺服器的整個請求之前把壓縮流轉向客戶端。
Nginx採用了一些os提供的最新特性如對sendfile (Linux 2.2+),accept-filter (FreeBSD 4.1+),TCP_DEFER_ACCEPT (Linux 2.4+) 的支持,從而大大提高了性能。

二. Nginx 安裝配置

1.安裝pcre
./configure

•  make && make install

•  cd ../
複製代碼3.nginx 編譯安裝
./configure --user=www --group=www --prefix=/usr/local/nginx/ --with-http_stub_status_module --with-openssl=/usr/local/openssl

•make && make install
複製代碼更詳細的模塊定製與安裝請參照官方wiki.

三. Nginx Rewrite

1.Nginx Rewrite 基本標記(flags)
last - 基本上都用這個Flag。

•break - 中止Rewirte,不在繼續匹配

•redirect - 返回臨時重定向的HTTP狀態302

•permanent - 返回永久重定向的HTTP狀態301
複製代碼2. 正則表達式匹配,其中:
    * ~  為區分大小寫匹配

•    * ~* 為不區分大小寫匹配

•    * !~和!~*分別為區分大小寫不匹配及不區分大小寫不匹配
複製代碼3. 文件及目錄匹配,其中:
    * -f和!-f用來判斷是否存在文件

•    * -d和!-d用來判斷是否存在目錄

•    * -e和!-e用來判斷是否存在文件或目錄

•    * -x和!-x用來判斷文件是否可執行
複製代碼
4.Nginx 的一些可用的全局變數,可用做條件判斷:

$args

•$content_length

•$content_type

•$document_root

•$document_uri

•$host

•$http_user_agent

•$http_cookie

•$limit_rate

•$request_body_file

•$request_method

•$remote_addr

•$remote_port

•$remote_user

•$request_filename

•$request_uri

•$query_string

•$scheme

•$server_protocol

•$server_addr

•$server_name

•$server_port

•$uri
複製代碼四.Nginx Redirect
將所有linuxtone.org與abc.linuxtone.org域名全部自跳轉到http://www.linuxtone.org
server

•{

•listen 80;

•server_name linuxtone.org abc.linuxtone.org;

•index index.html index.php;

•root /data/www/wwwroot;

•if ($http_host !~ "^www\.linxtone\.org$") {

•rewrite ^(.*) http://www.linuxtone.org$1 redirect;

•}



•........................

•}
複製代碼五.Nginx 目錄自動加斜線:
       if (-d $request_filename){

•           rewrite ^/(.*)([^/])$ http://$host/$1$2/ permanent;

•      }
複製代碼六.Nginx 防盜鏈
1.針對不同的文件類型
#Preventing hot linking of images and other file types

•location ~* ^.+\.(gif|jpg|png|swf|flv|rar|zip)$ {

•        valid_referers none blocked server_names *.linuxtone.org http://localhost baidu.com;

•if ($invalid_referer) {

•      rewrite   ^/   http://www.linuxtone.org/images/default/logo.gif;

•      #return   403;

•      }

•                      }

•}
複製代碼2.針對不同的目錄
location /img/ {

•    root /data/www/wwwroot/bbs/img/;

•    valid_referers none blocked server_names *.linuxtone.org http://localhost baidu.com;

•    if ($invalid_referer) {

•                   rewrite  ^/  http://www.linuxtone.org/images/default/logo.gif;

•                   #return   403;

•    }

•}
複製代碼3. 同實現防盜鏈和expires的方法
#Preventing hot linking of images and other file types

•location ~* ^.+\.(gif|jpg|png|swf|flv|rar|zip)$ {

•        valid_referers none blocked server_names *.linuxtone.org http://localhost baidu.com;

•if ($invalid_referer) {

•      rewrite   ^/   http://www.linuxtone.org/images/default/logo.gif;

•     #return   403;

•      }

•                      }

•     access_log off;

•     root /data/www/wwwroot/bbs;

•     expires 1d;

•     break;



•}
複製代碼七.Nginx expires

1.        根據文件類型expires

# Add expires header for static content

•location ~* \.(js|css|jpg|jpeg|gif|png|swf)$ {

•    if (-f $request_filename) {

•       root /data/www/wwwroot/bbs;

•       expires      1d;

•       break;

•    }

•}
複製代碼
2.根據判斷某個目錄
# serve static files

•location ~ ^/(images|javascript|js|css|flash|media|static)/  {

•root    /data/www/wwwroot/down;

•        expires 30d;

•  }
複製代碼八.Nginx 訪問控制

1.Nginx 身份證驗證
#cd /usr/local/nginx/conf

•#mkdir htpasswd

•/usr/local/apache2/bin/htpasswd -c /usr/local/nginx/conf/htpasswd/tongji linuxtone #添加用戶名為linuxtone

•New password:   (此處輸入你的密碼)

•Re-type new password:   (再次輸入你的密碼)

•Adding password for user



•http://count.linuxtone.org/tongji/data/index.html(目錄存在/data/www/wwwroot/tongji/data/目錄下)



•將下段配置放到虛擬主機目錄,當訪問http://count.linuxtone/tongji/即提示要密驗證:

•location ~ ^/(tongji)/  {

•                root    /data/www/wwwroot/count;

•                        auth_basic              "LT-COUNT-TongJi";

•                        auth_basic_user_file  /usr/local/nginx/conf/htpasswd/tongji;

•                }
複製代碼
2.Nginx 禁止訪問某類型的文件.

如,Nginx下禁止訪問*.txt文件,配置方法如下.
location ~* \.(txt|doc)$ {

•   if (-f $request_filename) {

•   root /data/www/wwwroot/linuxtone/test;

•   break;

•   }

•}
複製代碼方法2:
location ~* \.(txt|doc)${

•        root /data/www/wwwroot/linuxtone/test;

•        deny all;

•}
複製代碼禁止訪問某個目錄
location ~ ^/(WEB-INF)/ {

•            deny all;

•}  
複製代碼
3.使用ngx_http_access_module限制ip訪問
location / {

•    deny    192.168.1.1;

•    allow   192.168.1.0/24;

•    allow   10.1.1.0/16;

•    deny    all;

•}
複製代碼詳細參見wiki: http://wiki.codemongers.com/NginxHttpAccessModule#allow


4.Nginx 下載限制併發和速率
limit_zone   one  $binary_remote_addr  10m;

•server

•       {

•               listen       80;

•               server_name  down.linuxotne.org;

•               index index.html index.htm index.php;

•               root   /data/www/wwwroot/down;

•               #Zone limit

•               location / {

•                   limit_conn   one  1;

•                   limit_rate  20k;

•               }

•..........

•       }
複製代碼
5.        Nginx 實現Apache一樣目錄列表
location  /  {

•    autoindex  on;

•}
複製代碼九.Nginx Location

1.基本語法:[和上面rewrite正則匹配語法基本一致]
location [=|~|~*|^~] /uri/ { … }

•    * ~  為區分大小寫匹配

•    * ~* 為不區分大小寫匹配

•    * !~和!~*分別為區分大小寫不匹配及不區分大小寫不匹配
複製代碼示例1:
location = / {

•# matches the query / only.

•# 只匹配 / 查詢。

•}
複製代碼匹配任何查詢,因為所有請求都已 / 開頭。但是正則表達式規則和長的塊規則將被優先和查詢匹配
示例2:
location ^~ /images/ {

•# matches any query beginning with /images/ and halts searching,

•# so regular expressions will not be checked.
複製代碼# 匹配任何已 /images/ 開頭的任何查詢並且停止搜索。任何正則表達式將不會被測試。
示例3:
location ~* \.(gif|jpg|jpeg)$ {

•# matches any request ending in gif, jpg, or jpeg. However, all

•# requests to the /images/ directory will be handled by

•}
複製代碼# 匹配任何已 gif、jpg 或 jpeg 結尾的請求。

十.Nginx 日誌處理
1.Nginx 日誌切割#contab -e

•59 23 * * * /usr/local/sbin/logcron.sh /dev/null 2>&1
複製代碼# cat /usr/local/sbin/logcron.sh
#!/bin/bash

•log_dir="/data/logs"

•time=`date +%Y%m%d`  

•/bin/mv  ${log_dir}/access_linuxtone.org.log ${log_dir}/access_count.linuxtone.org.$time.log

•kill -USR1 `cat  /var/run/nginx.pid`
複製代碼更多的日誌分析與處理就關注(同時歡迎你參加討論):http://bbs.linuxtone.org/forum-8-1.html


2.Nginx 如何不記錄部分日誌

日誌太多,每天好幾個G,少記錄一些,下面的配置寫到server{}段中就可以了
location ~ .*\.(js|jpg|JPG|jpeg|JPEG|css|bmp|gif|GIF)$

•{

•     access_log off;

•}
複製代碼十一.Nginx Cache服務配置
如果需要將文件緩存到本地,則需要增加如下幾個子參數:
proxy_store on;

•proxy_store_access user:rw group:rw all:rw;

•proxy_temp_path 緩存目錄;
複製代碼其中,
proxy_store on用來啟用緩存到本地的功能,
proxy_temp_path用來指定緩存在哪個目錄下,如:proxy_temp_path html;

在經過上一步配置之後,雖然文件被緩存到了本地磁碟上,但每次請求仍會向遠端拉取文件,為了避免去遠端拉取文件,必須修改proxy_pass:
if ( !-e $request_filename) {

•    proxy_pass  http://mysvr;

•}
複製代碼即改成有條件地去執行proxy_pass,這個條件就是當請求的文件在本地的proxy_temp_path指定的目錄下不存在時,再向後端拉取。

十二.Nginx 負載均衡
1. Nginx 基礎知識
nginx的upstream目前支持4種方式的分配

1)、輪詢(默認)

每個請求按時間順序逐一分配到不同的後端伺服器,如果後端伺服器down掉,能自動剔除。

2)、weight

指定輪詢幾率,weight和訪問比率成正比,用於後端伺服器性能不均的情況。

2)、ip_hash

每個請求按訪問ip的hash結果分配,這樣每個訪客固定訪問一個後端伺服器,可以解決session的問題。

3)、fair(第三方)

按後端伺服器的響應時間來分配請求,響應時間短的優先分配。

4)、url_hash(第三方)

3.Nginx 負載均衡實例1
upstream bbs.linuxtone.org {#定義負載均衡設備的Ip及設備狀態

•    server 127.0.0.1:9090 down;

•    server 127.0.0.1:8080 weight=2;

•    server 127.0.0.1:6060;

•    server 127.0.0.1:7070 backup;

•}
複製代碼在需要使用負載均衡的server中增加
proxy_pass http://bbs.linuxtone.org/;
複製代碼每個設備的狀態設置為:
1.down 表示單前的server暫時不參與負載

•2.weight 默認為1.weight越大,負載的權重就越大。

•3.max_fails :允許請求失敗的次數默認為1.當超過最大次數時,返回proxy_next_upstream 模塊定義的錯誤

•4.fail_timeout:max_fails次失敗后,暫停的時間。

•5.backup: 其它所有的非backup機器down或者忙的時候,請求backup機器。所以這台機器壓力會最輕。
複製代碼nginx支持同時設置多組的負載均衡,用來給不用的server來使用。

client_body_in_file_only 設置為On 可以講client post過來的數據記錄到文件中用來做debug
client_body_temp_path 設置記錄文件的目錄 可以設置最多3層目錄
location 對URL進行匹配.可以進行重定向或者進行新的代理 負載均衡

4.Nginx 負載均衡實例 2
按訪問url的hash結果來分配請求,使每個url定向到同一個後端伺服器,後端伺服器為緩存時比較有效,也可以用作提高Squid緩存命中率.

簡單的負載均等實例:
#vi nginx.conf  //nginx主配置文件核心配置
……….

•#loadblance my.linuxtone.org

•       upstream  my.linuxtone.org  {

•       ip_hash;

•       server   127.0.0.1:8080;

•       server   192.168.169.136:8080;

•       server   219.101.75.138:8080;

•       server   192.168.169.117;

•       server   192.168.169.118;

•       server   192.168.169.119;

•     }

•…………..

•include          vhosts/linuxtone_lb.conf;

•………

•#vi proxy.conf

•proxy_redirect off;

•proxy_set_header Host $host;

•proxy_set_header X-Real-IP $remote_addr;

•proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

•client_max_body_size 50m;

•client_body_buffer_size 256k;

•proxy_connect_timeout 30;

•proxy_send_timeout 30;

•proxy_read_timeout 60;



•proxy_buffer_size 4k;

•proxy_buffers 4 32k;

•proxy_busy_buffers_size 64k;

•proxy_temp_file_write_size 64k;

•proxy_next_upstream error timeout invalid_header http_500 http_503 http_404;

•proxy_max_temp_file_size 128m;

•proxy_store on;

•proxy_store_access   user:rw  group:rw  all:r;

•#nginx cache               

•client_body_temp_path  /data/nginx_cache/client_body 1 2;

•proxy_temp_path /data/nginx_cache/proxy_temp 1 2;
複製代碼#vi linuxtone_lb.conf
server

•    {

•        listen  80;

•        server_name my.linuxtone.org;

•        index index.php;

•        root /data/www/wwwroot/mylinuxtone;

•        if (-f $request_filename) {

•            break;

•           }

•        if (-f $request_filename/index.php) {

•          rewrite (.*) $1/index.php break;

•        }



•        error_page 403 http://my.linuxtone.org/member.php?m=user&a=login;

•        location / {

•           if ( !-e $request_filename) {

•               proxy_pass http://my.linuxtone.org;

•               break;

•           }

•           include /usr/local/nginx/conf/proxy.conf;

•        }

•}
複製代碼十三.Nginx 優化

1.減小nginx編譯后的文件大小 (Reduce file size of nginx)
默認的nginx編譯選項里居然是用debug模式(-g)的(debug模式會插入很多跟蹤和ASSERT之類),編譯以後一個nginx有好幾兆。去掉nginx的debug模式編譯,編譯以後只有幾百K
在 auto/cc/gcc,最後幾行有:
# debug
CFLAGS=」$CFLAGS -g」
註釋掉或刪掉這幾行,重新編譯即可。


2.修改Nginx的header偽裝伺服器
# cd nginx-0.6.31

•# vi src/core/nginx.h

•#ifndef _NGINX_H_INCLUDED_

•#define _NGINX_H_INCLUDED_





•#define NGINX_VERSION      "1.3"

•#define NGINX_VER          "LTWS/" NGINX_VERSION



•#define NGINX_VAR          "NGINX"

•#define NGX_OLDPID_EXT     ".oldbin"





•#endif /* _NGINX_H_INCLUDED_ */



•# curl -I my.linuxtone.org

•HTTP/1.1 200 OK

•Server: LTWS/1.3

•Date: Mon, 24 Nov 2008 02:42:51 GMT

•Content-Type: text/html; charset=utf8

•Transfer-Encoding: chunked

•Connection: keep-alive        

•                        
複製代碼十四.Nginx 相關參考文檔

1.Nginx Debug技巧
/usr/local/nginx/sbin/nginx ?t 調試配置是否有語法錯誤。
《解決方案》

謝謝分享ngins學習中...

[火星人 ] Nginx 常見應用技術指南(Nginx Tips)已經有910次圍觀

http://coctec.com/docs/service/show-post-2004.html