2012年10月3日 星期三

Nginx 反向代理與Rewite

以下為筆記 :p
延續上次的設定

反向代理 

利用proxy_pass來設定欲導向的服務
修改/etc/nginx/conf.d 底下的設定檔
我在此新增一個localnginx.conf的設定檔
server {
    listen       80;
    server_name  localnginx1;
    
    charset utf-8;
    
    location / {
        proxy_pass http://127.0.0.1:3000;
    }
}

listen跟server_name請看上篇
重點在於 location / 的部份
 / 代表根目錄
也就是在網址輸入 http://localnginx1/ 的時候
要處理的動作
這裡我使用 proxy_pass 把 client 端發出的 Request
轉發到 3000 port 的 service

Url Rewrite 
rewrite 可以接兩個參數
第一個參數設下條件
第二個參數則設定目標
server {
    listen       80;
    server_name  localnginx2;
    
    charset utf-8;

    location / {
        rewrite  ^(.*) http://127.0.0.1:3000;
    }
    
    location /google {
        rewrite ^ http://www.google.com.tw;
    }
}

按照上面的方式設定
輸入 http://localnginx2/ 時
會導向 http://127.0.0.1:3000; 並改變網址

輸入 http://localnginx2/google 時
會導向 google 台灣首頁


Nginx Virtual Host 設定

最近開始碰Nginx 紀錄一下設定的部份 環境為FC17 kernel: 3.5.3-1.fc17.i686.PAE 安裝好Nginx後 先設定為開機啟動 在Terminal上輸入
systemctl enable nginx.service
成功之後 輸入啟動指令
systemctl start nginx.service

完成後輸入在瀏覽器網址列上輸入localhost應該就能看到Nginx的歡迎頁面了


接下來為了測試方便 我們使用修改 hostname 的方式來模擬 sub domain 的部份 先編輯 /etc/hosts

如上圖所示, 在127.0.0.1那行加上 localnginx ~ localnginx2 三個name來測試 設定完畢就開始進入Nginx的設定了 Nginx的conf檔置於 /etc/nginx/conf.d/底下 只要在此目錄下的.conf檔案都會在Nginx啟動時載入 新增一個設定檔
vim /etc/conf.d/localnginx.conf

server {
    listen       80;
    server_name  localnginx;

    charset utf-8;

    location / {
        root   /home/sean/nginx/;
        index  index.html index.htm;
    }
}
此設定檔設定偵聽 80 port 並在遇到server name為localnginx時 使用此設定檔 粗體的部份就是設定此server的初始目錄在哪 存檔完畢後輸入重新啟動nginx
systemctl reload nginx.service
在對應的目錄底下放入index.html後 如此一來在瀏覽器上就能看到結果囉