使用nginx負載均衡nodejs

weixin_34208283發表於2018-02-01

個人部落格: http://zhangsunyucong.top

前言

這篇文章適合熟悉nodejs的同學觀看。主要是關於如何使用nginx做反向代理和負載均衡nodejs的多個例項的配置流程,nodejs例項可以是分佈在同一臺主機上或者不同的主機上的多個例項。

主要內容有

  • 在同一主機建立nodejs多個例項
  • 詳細講解ngnix.conf檔案的每項配置的作用

在同一主機建立nodejs多個例項

我的nodejs環境:

  • window 7 64位
  • nodejs v8.1.3
  • webstorm 2017版

根目錄/server.js檔案

'use strict';

var express = require('express');
var timeout = require('connect-timeout');
var path = require('path');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

var app = express();

// 設定模板引擎,路徑在根目錄+public中
app.set('views', path.join(__dirname, 'public'));
app.set('view engine', 'ejs');

app.use(express.static('public'));

app.use(express.static(path.join(__dirname, 'public')));

// 設定預設超時時間
app.use(timeout('15s'));
//請求體
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
//cookie
app.use(cookieParser());
//註冊HTTP訊息頭部資訊
app.use(
    function(req, res, next) {
        res.set(
            {
                'Content-Type': 'text/html',
                'Access-Control-Allow-Origin': '*',
                'Access-Control-Allow-Rememberme': true,
                'Access-Control-Allow-HttpOnly': false,
                'Access-Control-Allow-Methods': 'POST, GET, PUT, DELETE, OPTIONS',
                'Access-Control-Allow-Credentials': true, //false,
                'Access-Control-Max-Age': '86400', // 24 hours
                'Access-Control-Allow-Headers': 'X-Requested-With, X-HTTP-Method-Override, Content-Type, Accept'
            }
        );

        //decodeURI(req.url)
        console.log('%s %s', req.method, req.url);
        next();
    }
);

//首頁
app.get('/', function(req, res) {
    res.render('index1', { currentTime: new Date() });
});

app.use(function(req, res, next) {
    // 如果任何一個路由都沒有返回響應,則丟擲一個 404 異常給後續的異常處理器
    if (!res.headersSent) {
        var err = new Error('Not Found');
        err.status = 404;
        next(err);
    }
});

// 錯誤處理
app.use(function(err, req, res, next) {
    if (req.timedout && req.headers.upgrade === 'websocket') {
        // 忽略 websocket 的超時
        return;
    }

    var statusCode = err.status || 500;
    if (statusCode === 500) {
        console.error(err.stack || err);
    }
    if (req.timedout) {
        console.error('請求超時: url=%s, timeout=%d, 請確認方法執行耗時很長,或沒有正確的 response 回撥。', req.originalUrl, err.timeout);
    }
    res.status(statusCode);
    // 預設不輸出異常詳情
    var error = {};
    if (app.get('env') === 'development') {
        // 如果是開發環境,則將異常堆疊輸出到頁面,方便開發除錯
        error = err;
    }
    res.render('error', {
        message: err.message,
        error: error
    });
});

function catchGlobalError(err) {
    // 註冊全域性未捕獲異常處理器
    process.on('uncaughtException', function(err) {
        console.error('Caught exception:', err.stack);
    });
    process.on('unhandledRejection', function(reason, p) {
        console.error('Unhandled Rejection at: Promise ', p, ' reason: ', reason.stack);
    });
}

//建立兩個伺服器實體
var server = require('http').createServer(app);
var server1 = require('http').createServer(app);

//伺服器監聽埠
var PORT = parseInt(process.env.PORT || 3000);
var PORT1 = PORT + 1;

server.listen(PORT, function (err) {
    console.log('Node app is running on port:', PORT);
    catchGlobalError(err);
});

server1.listen(PORT1, function (err) {
    console.log('Node app is running on port:', PORT1);
    catchGlobalError(err);
});

根目錄/views/error.ejs

<!DOCTYPE HTML>
<html>
  <head>
    <title>Error</title>
    <link rel="stylesheet" href="/stylesheets/style.css">
  </head>
  <body>
    <h1><%= message %></h1>
    <h2><%= error.status %></h2>
    <pre><%= error.stack %></pre>
  </body>
</html>

根目錄/views/index.ejs

<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">

  <title>nodejs 和 nginx</title>
    
  <link rel="stylesheet" href="./stylesheets/style.css">

</head>
      <body>
      <p><h3>Hello world</h3></p>
      </body>
</html>

ngnix配置檔案

nginx.config

#user  nobody;
worker_processes  1;

#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;

#pid        logs/nginx.pid;


events {
    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;

    sendfile        on;
    #tcp_nopush     on;

    #keepalive_timeout  0;
    keepalive_timeout  65;

    #gzip  on;
    
    upstream nodeproxy {
        server 192.168.10.137:3000 weight=10;       
        server 127.0.0.1:3001 weight=12;   
    }

    server {
        listen       8089;
        server_name  localhost;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

        location / {
            root   html;
            index  index.html index.htm;
            proxy_pass  http://nodeproxy; #與upstream的名稱一致
            proxy_redirect  default; 
        }

        #error_page  404              /404.html;

        # redirect server error pages to the static page /50x.html
        #
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }

        # proxy the PHP scripts to Apache listening on 127.0.0.1:80
        #
        #location ~ \.php$ {
        #    proxy_pass   http://127.0.0.1;
        #}

        # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
        #
        #location ~ \.php$ {
        #    root           html;
        #    fastcgi_pass   127.0.0.1:9000;
        #    fastcgi_index  index.php;
        #    fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;
        #    include        fastcgi_params;
        #}

        # deny access to .htaccess files, if Apache's document root
        # concurs with nginx's one
        #
        #location ~ /\.ht {
        #    deny  all;
        #}
    }


    # another virtual host using mix of IP-, name-, and port-based configuration
    #
    #server {
    #    listen       8000;
    #    listen       somename:8080;
    #    server_name  somename  alias  another.alias;

    #    location / {
    #        root   html;
    #        index  index.html index.htm;
    #    }
    #}


    # HTTPS server
    #
    #server {
    #    listen       443 ssl;
    #    server_name  localhost;

    #    ssl_certificate      cert.pem;
    #    ssl_certificate_key  cert.key;

    #    ssl_session_cache    shared:SSL:1m;
    #    ssl_session_timeout  5m;

    #    ssl_ciphers  HIGH:!aNULL:!MD5;
    #    ssl_prefer_server_ciphers  on;

    #    location / {
    #        root   html;
    #        index  index.html index.htm;
    #    }
    #}

}

nginx常用命令

在nginx的安裝根目錄下,開啟命令列工具,執行。

啟動nginx:start nginx
重新載入配置:nginx -s reload
重新開啟日誌:nginx -s reopen

關閉nginx:
快速停止:nginx -s stop
有序關閉:nginx -s quit

如果遇到啟動不了nginx,可能是監聽的埠被佔用。
使用命令:netstat -aon | findstr :80
查詢一下

用瀏覽器訪問localhost:8089,我的測試的結果是:

"D:\WebStorm 2017.2.1\bin\runnerw.exe" D:\nodejs\node.exe D:\collect\leancloud\jiangebuluo\NodeTestDemo\myServer.js
Node app is running on port: 3000
Node app is running on port: 3001
伺服器監聽的IP: 192.168.10.137
伺服器監聽的IP: 192.168.10.137
伺服器監聽的IP: 127.0.0.1
伺服器監聽的IP: 127.0.0.1
伺服器監聽的IP: 127.0.0.1
伺服器監聽的IP: 127.0.0.1
伺服器監聽的IP: 127.0.0.1
伺服器監聽的IP: 127.0.0.1
伺服器監聽的IP: 192.168.10.137
伺服器監聽的IP: 192.168.10.137


最後

另外貼出一個ubuntu的詳細配置講解。來自獵手家園的部落格

#定義Nginx執行的使用者和使用者組
user www www;

#nginx程式數,建議設定為等於CPU總核心數。
worker_processes 8;
 
#全域性錯誤日誌定義型別,[ debug | info | notice | warn | error | crit ]
error_log /usr/local/nginx/logs/error.log info;

#程式pid檔案
pid /usr/local/nginx/logs/nginx.pid;

#指定程式可以開啟的最大描述符:數目
#工作模式與連線數上限
#這個指令是指當一個nginx程式開啟的最多檔案描述符數目,理論值應該是最多開啟檔案數(ulimit -n)與nginx程式數相除,但是nginx分配請求並不是那麼均勻,所以最好與ulimit -n 的值保持一致。
#現在在linux 2.6核心下開啟檔案開啟數為65535,worker_rlimit_nofile就相應應該填寫65535。
#這是因為nginx排程時分配請求到程式並不是那麼的均衡,所以假如填寫10240,總併發量達到3-4萬時就有程式可能超過10240了,這時會返回502錯誤。
worker_rlimit_nofile 65535;


events
{
    #參考事件模型,use [ kqueue | rtsig | epoll | /dev/poll | select | poll ]; epoll模型
    #是Linux 2.6以上版本核心中的高效能網路I/O模型,linux建議epoll,如果跑在FreeBSD上面,就用kqueue模型。
    #補充說明:
    #與apache相類,nginx針對不同的作業系統,有不同的事件模型
    #A)標準事件模型
    #Select、poll屬於標準事件模型,如果當前系統不存在更有效的方法,nginx會選擇select或poll
    #B)高效事件模型
    #Kqueue:使用於FreeBSD 4.1+, OpenBSD 2.9+, NetBSD 2.0 和 MacOS X.使用雙處理器的MacOS X系統使用kqueue可能會造成核心崩潰。
    #Epoll:使用於Linux核心2.6版本及以後的系統。
    #/dev/poll:使用於Solaris 7 11/99+,HP/UX 11.22+ (eventport),IRIX 6.5.15+ 和 Tru64 UNIX 5.1A+。
    #Eventport:使用於Solaris 10。 為了防止出現核心崩潰的問題, 有必要安裝安全補丁。
    use epoll;

    #單個程式最大連線數(最大連線數=連線數*程式數)
    #根據硬體調整,和前面工作程式配合起來用,儘量大,但是別把cpu跑到100%就行。每個程式允許的最多連線數,理論上每臺nginx伺服器的最大連線數為。
    worker_connections 65535;

    #keepalive超時時間。
    keepalive_timeout 60;

    #客戶端請求頭部的緩衝區大小。這個可以根據你的系統分頁大小來設定,一般一個請求頭的大小不會超過1k,不過由於一般系統分頁都要大於1k,所以這裡設定為分頁大小。
    #分頁大小可以用命令getconf PAGESIZE 取得。
    #[root@web001 ~]# getconf PAGESIZE
    #4096
    #但也有client_header_buffer_size超過4k的情況,但是client_header_buffer_size該值必須設定為“系統分頁大小”的整倍數。
    client_header_buffer_size 4k;

    #這個將為開啟檔案指定快取,預設是沒有啟用的,max指定快取數量,建議和開啟檔案數一致,inactive是指經過多長時間檔案沒被請求後刪除快取。
    open_file_cache max=65535 inactive=60s;

    #這個是指多長時間檢查一次快取的有效資訊。
    #語法:open_file_cache_valid time 預設值:open_file_cache_valid 60 使用欄位:http, server, location 這個指令指定了何時需要檢查open_file_cache中快取專案的有效資訊.
    open_file_cache_valid 80s;

    #open_file_cache指令中的inactive引數時間內檔案的最少使用次數,如果超過這個數字,檔案描述符一直是在快取中開啟的,如上例,如果有一個檔案在inactive時間內一次沒被使用,它將被移除。
    #語法:open_file_cache_min_uses number 預設值:open_file_cache_min_uses 1 使用欄位:http, server, location  這個指令指定了在open_file_cache指令無效的引數中一定的時間範圍內可以使用的最小檔案數,如果使用更大的值,檔案描述符在cache中總是開啟狀態.
    open_file_cache_min_uses 1;
    
    #語法:open_file_cache_errors on | off 預設值:open_file_cache_errors off 使用欄位:http, server, location 這個指令指定是否在搜尋一個檔案是記錄cache錯誤.
    open_file_cache_errors on;
}
 
 
 
#設定http伺服器,利用它的反向代理功能提供負載均衡支援
http
{
    #副檔名與檔案型別對映表
    include mime.types;

    #預設檔案型別
    default_type application/octet-stream;

    #預設編碼
    #charset utf-8;

    #伺服器名字的hash表大小
    #儲存伺服器名字的hash表是由指令server_names_hash_max_size 和server_names_hash_bucket_size所控制的。引數hash bucket size總是等於hash表的大小,並且是一路處理器快取大小的倍數。在減少了在記憶體中的存取次數後,使在處理器中加速查詢hash表鍵值成為可能。如果hash bucket size等於一路處理器快取的大小,那麼在查詢鍵的時候,最壞的情況下在記憶體中查詢的次數為2。第一次是確定儲存單元的地址,第二次是在儲存單元中查詢鍵 值。因此,如果Nginx給出需要增大hash max size 或 hash bucket size的提示,那麼首要的是增大前一個引數的大小.
    server_names_hash_bucket_size 128;

    #客戶端請求頭部的緩衝區大小。這個可以根據你的系統分頁大小來設定,一般一個請求的頭部大小不會超過1k,不過由於一般系統分頁都要大於1k,所以這裡設定為分頁大小。分頁大小可以用命令getconf PAGESIZE取得。
    client_header_buffer_size 32k;

    #客戶請求頭緩衝大小。nginx預設會用client_header_buffer_size這個buffer來讀取header值,如果header過大,它會使用large_client_header_buffers來讀取。
    large_client_header_buffers 4 64k;

    #設定通過nginx上傳檔案的大小
    client_max_body_size 8m;

    #開啟高效檔案傳輸模式,sendfile指令指定nginx是否呼叫sendfile函式來輸出檔案,對於普通應用設為 on,如果用來進行下載等應用磁碟IO重負載應用,可設定為off,以平衡磁碟與網路I/O處理速度,降低系統的負載。注意:如果圖片顯示不正常把這個改成off。
    #sendfile指令指定 nginx 是否呼叫sendfile 函式(zero copy 方式)來輸出檔案,對於普通應用,必須設為on。如果用來進行下載等應用磁碟IO重負載應用,可設定為off,以平衡磁碟與網路IO處理速度,降低系統uptime。
    sendfile on;

    #開啟目錄列表訪問,合適下載伺服器,預設關閉。
    autoindex on;

    #此選項允許或禁止使用socke的TCP_CORK的選項,此選項僅在使用sendfile的時候使用
    tcp_nopush on;
     
    tcp_nodelay on;

    #長連線超時時間,單位是秒
    keepalive_timeout 120;

    #FastCGI相關引數是為了改善網站的效能:減少資源佔用,提高訪問速度。下面引數看字面意思都能理解。
    fastcgi_connect_timeout 300;
    fastcgi_send_timeout 300;
    fastcgi_read_timeout 300;
    fastcgi_buffer_size 64k;
    fastcgi_buffers 4 64k;
    fastcgi_busy_buffers_size 128k;
    fastcgi_temp_file_write_size 128k;

    #gzip模組設定
    gzip on; #開啟gzip壓縮輸出
    gzip_min_length 1k;    #最小壓縮檔案大小
    gzip_buffers 4 16k;    #壓縮緩衝區
    gzip_http_version 1.0;    #壓縮版本(預設1.1,前端如果是squid2.5請使用1.0)
    gzip_comp_level 2;    #壓縮等級
    gzip_types text/plain application/x-javascript text/css application/xml;    #壓縮型別,預設就已經包含textml,所以下面就不用再寫了,寫上去也不會有問題,但是會有一個warn。
    gzip_vary on;

    #開啟限制IP連線數的時候需要使用
    #limit_zone crawler $binary_remote_addr 10m;



    #負載均衡配置
    upstream piao.jd.com {
     
        #upstream的負載均衡,weight是權重,可以根據機器配置定義權重。weigth參數列示權值,權值越高被分配到的機率越大。
        server 127.0.0.1:3000 weight=3;
        server 127.0.0.1:3001 weight=2;

        #nginx的upstream目前支援4種方式的分配
        #1、輪詢(預設)
        #每個請求按時間順序逐一分配到不同的後端伺服器,如果後端伺服器down掉,能自動剔除。
        #2、weight
        #指定輪詢機率,weight和訪問比率成正比,用於後端伺服器效能不均的情況。
        #例如:
        #upstream bakend {
        #    server 192.168.0.14 weight=10;
        #    server 192.168.0.15 weight=10;
        #}
        #2、ip_hash
        #每個請求按訪問ip的hash結果分配,這樣每個訪客固定訪問一個後端伺服器,可以解決session的問題。
        #例如:
        #upstream bakend {
        #    ip_hash;
        #    server 192.168.0.14:88;
        #    server 192.168.0.15:80;
        #}
        #3、fair(第三方)
        #按後端伺服器的響應時間來分配請求,響應時間短的優先分配。
        #upstream backend {
        #    server server1;
        #    server server2;
        #    fair;
        #}
        #4、url_hash(第三方)
        #按訪問url的hash結果來分配請求,使每個url定向到同一個後端伺服器,後端伺服器為快取時比較有效。
        #例:在upstream中加入hash語句,server語句中不能寫入weight等其他的引數,hash_method是使用的hash演算法
        #upstream backend {
        #    server squid1:3128;
        #    server squid2:3128;
        #    hash $request_uri;
        #    hash_method crc32;
        #}

        #tips:
        #upstream bakend{#定義負載均衡裝置的Ip及裝置狀態}{
        #    ip_hash;
        #    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://bakend/;

        #每個裝置的狀態設定為:
        #1.down表示單前的server暫時不參與負載
        #2.weight為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進行匹配.可以進行重定向或者進行新的代理 負載均衡
    }
     
     
     
    #虛擬主機的配置
    server
    {
        #監聽埠
        listen 80;

        #域名可以有多個,用空格隔開
        server_name www.jd.com jd.com;
        index index.html index.htm index.php;
        root /data/www/jd;

        #對******進行負載均衡
        location ~ .*.(php|php5)?$
        {
            fastcgi_pass 127.0.0.1:9000;
            fastcgi_index index.php;
            include fastcgi.conf;
        }
         
        #圖片快取時間設定
        location ~ .*.(gif|jpg|jpeg|png|bmp|swf)$
        {
            expires 10d;
        }
         
        #JS和CSS快取時間設定
        location ~ .*.(js|css)?$
        {
            expires 1h;
        }
         
        #日誌格式設定
        #$remote_addr與$http_x_forwarded_for用以記錄客戶端的ip地址;
        #$remote_user:用來記錄客戶端使用者名稱稱;
        #$time_local: 用來記錄訪問時間與時區;
        #$request: 用來記錄請求的url與http協議;
        #$status: 用來記錄請求狀態;成功是200,
        #$body_bytes_sent :記錄傳送給客戶端檔案主體內容大小;
        #$http_referer:用來記錄從那個頁面連結訪問過來的;
        #$http_user_agent:記錄客戶瀏覽器的相關資訊;
        #通常web伺服器放在反向代理的後面,這樣就不能獲取到客戶的IP地址了,通過$remote_add拿到的IP地址是反向代理伺服器的iP地址。反向代理伺服器在轉發請求的http頭資訊中,可以增加x_forwarded_for資訊,用以記錄原有客戶端的IP地址和原來客戶端的請求的伺服器地址。
        log_format access '$remote_addr - $remote_user [$time_local] "$request" '
        '$status $body_bytes_sent "$http_referer" '
        '"$http_user_agent" $http_x_forwarded_for';
         
        #定義本虛擬主機的訪問日誌
        access_log  /usr/local/nginx/logs/host.access.log  main;
        access_log  /usr/local/nginx/logs/host.access.404.log  log404;
         
        #對 "/" 啟用反向代理
        location / {
            proxy_pass http://127.0.0.1:88;
            proxy_redirect off;
            proxy_set_header X-Real-IP $remote_addr;
             
            #後端的Web伺服器可以通過X-Forwarded-For獲取使用者真實IP
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
             
            #以下是一些反向代理的配置,可選。
            proxy_set_header Host $host;

            #允許客戶端請求的最大單檔案位元組數
            client_max_body_size 10m;

            #緩衝區代理緩衝使用者端請求的最大位元組數,
            #如果把它設定為比較大的數值,例如256k,那麼,無論使用firefox還是IE瀏覽器,來提交任意小於256k的圖片,都很正常。如果註釋該指令,使用預設的client_body_buffer_size設定,也就是作業系統頁面大小的兩倍,8k或者16k,問題就出現了。
            #無論使用firefox4.0還是IE8.0,提交一個比較大,200k左右的圖片,都返回500 Internal Server Error錯誤
            client_body_buffer_size 128k;

            #表示使nginx阻止HTTP應答程式碼為400或者更高的應答。
            proxy_intercept_errors on;

            #後端伺服器連線的超時時間_發起握手等候響應超時時間
            #nginx跟後端伺服器連線超時時間(代理連線超時)
            proxy_connect_timeout 90;

            #後端伺服器資料回傳時間(代理髮送超時)
            #後端伺服器資料回傳時間_就是在規定時間之內後端伺服器必須傳完所有的資料
            proxy_send_timeout 90;

            #連線成功後,後端伺服器響應時間(代理接收超時)
            #連線成功後_等候後端伺服器響應時間_其實已經進入後端的排隊之中等候處理(也可以說是後端伺服器處理請求的時間)
            proxy_read_timeout 90;

            #設定代理伺服器(nginx)儲存使用者頭資訊的緩衝區大小
            #設定從被代理伺服器讀取的第一部分應答的緩衝區大小,通常情況下這部分應答中包含一個小的應答頭,預設情況下這個值的大小為指令proxy_buffers中指定的一個緩衝區的大小,不過可以將其設定為更小
            proxy_buffer_size 4k;

            #proxy_buffers緩衝區,網頁平均在32k以下的設定
            #設定用於讀取應答(來自被代理伺服器)的緩衝區數目和大小,預設情況也為分頁大小,根據作業系統的不同可能是4k或者8k
            proxy_buffers 4 32k;

            #高負荷下緩衝大小(proxy_buffers*2)
            proxy_busy_buffers_size 64k;

            #設定在寫入proxy_temp_path時資料的大小,預防一個工作程式在傳遞檔案時阻塞太長
            #設定快取資料夾大小,大於這個值,將從upstream伺服器傳
            proxy_temp_file_write_size 64k;
        }
         
         
        #設定檢視Nginx狀態的地址
        location /NginxStatus {
            stub_status on;
            access_log on;
            auth_basic "NginxStatus";
            auth_basic_user_file confpasswd;
            #htpasswd檔案的內容可以用apache提供的htpasswd工具來產生。
        }
         
        #本地動靜分離反向代理配置
        #所有jsp的頁面均交由tomcat或resin處理
        location ~ .(jsp|jspx|do)?$ {
            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_pass http://127.0.0.1:8080;
        }
         
        #所有靜態檔案由nginx直接讀取不經過tomcat或resin
        location ~ .*.(htm|html|gif|jpg|jpeg|png|bmp|swf|ioc|rar|zip|txt|flv|mid|doc|ppt|
        pdf|xls|mp3|wma)$
        {
            expires 15d; 
        }
         
        location ~ .*.(js|css)?$
        {
            expires 1h;
        }
    }
}

相關文章