顯示具有 nginx 標籤的文章。 顯示所有文章
顯示具有 nginx 標籤的文章。 顯示所有文章

2012/08/26

Nginx load balance

Nginx 內建的 load balance 規則有 round-robin、weight、ip_hash、fair、url_hash
但如果想更精確的把特定 request 導到特定的 server,可以自己來寫 rule。

例如想用 user id 做 despatch,下面的例子是利用 user id 的開頭第一個字元來做決定
server {
    listen 80;
    server_name www.domain.com;

    location ~* /profile/[a-m] {
        proxy_pass http://server0.domain.com;
    }

    location ~* /profile/[n-z] {
        proxy_pass http://server1.domain.com;
    }    
}

如此一來
http://www.domain.com/brian 就會導向 server0
http://www.domain.com/vicky 就會導向 server1



如果 user id 是流水號,那我們就判斷 id 的個位數字
server {
    listen 80;
    server_name www.domain.com;

    location ~* /profile/[0-9]*[02468]$ {
        proxy_read_timeout 10s;
        proxy_pass http://server0.domain.com;
    }

    location ~* /profile/[0-9]*[13579]$ {
        proxy_pass http://server1.domain.com;
    }
}

http://www.domain.com/2000 就會導向 server0
http://www.domain.com/2001 就會導向 server1



如果 request 是 http long polling,可以考慮用301 Moved Permanently 的方式讓 client 的 connection keep 在 target server,減少 nginx 的 connection 數量
server {
    listen 80;
    server_name www.my-domain.com;

    location ~* /profile/[a-m] {
        rewrite ^(.*) http://server0.domain.com$1 permanent;
    }

    location ~* /profile/[n-z] {
        rewrite ^(.*) http://server1.domain.com$1 permanent;
    }    
}

有關 location rule 可以參考:高飞鸟 – Highbird » Blog Archive » Nginx的location匹配规则

2012/04/18

Nginx 加速 web 存取速度

對於靜態資料不外乎就是 cache、CDN (Content delivery network),減少後端 server 的 loading。

讓 static content 去別台抓
location ^~ /static {
    proxy_pass http://cdn.server/static;
}

讓 static conetent 由 nginx 處理,不透過後端 http server
location ^~ /static {
    root /var/www
}

承上,並加入 cache 機制,第一次會去檔案讀取,之後就從 cache 讀取 (要注意 cache refresh的問題)
location ^~ /static {
    root /var/www;
    proxy_buffering on;
    proxy_cache_valid 200 120m;
    expires 30d;
}

如果 static file 在多個目錄,用 OR 的方式去match
location ~* (/images|/css|/js) {
   ...
}

如果 static file 分佈在各個目錄,可以利用下面的 rule 去 match 附檔名
location ~* \.(jpg|png|gif|jpeg|css|js|mp3|wav|swf|mov|doc|pdf|xls|ppt|docx|pptx|xlsx)$ {
   ...
}

2012/02/26

Nginx 基本設定教學

下載與安裝:http://wiki.nginx.org/Install
若 make 的時候出現下面錯誤
make -f objs/Makefile
make[1]: Entering directory `/home/user/src/server/nginx-1.0.14'
cd /usr/lib \
        && if [ -f Makefile ]; then make distclean; fi \
        && CC="gcc" CFLAGS="-O2 -fomit-frame-pointer -pipe " \
        ./configure --disable-shared
/bin/sh: line 2: ./configure: No such file or directory
make[1]: *** [/usr/lib/Makefile] Error 127
make[1]: Leaving directory `/home/user/src/server/nginx-1.0.14'
make: *** [build] Error 2
解決方式:
在 configure 時 --with-pcre 指向 pcre 的 source tree
$ ./configure --with-pcre=~/pcre-8.30
$ make 


基本指令

# 啟動
/usr/local/nginx/sbin/nginx

# 停止
/usr/local/nginx/sbin/nginx -s stop

# Reload
/usr/local/nginx/sbin/nginx -s reload

# 編輯設定檔
vim /usr/local/nginx/conf/nginx.conf

# 檢查設定檔
/usr/local/nginx/sbin/nginx -t


下面列出幾種常用的模式: