NGINX 緩存動態頁面,以及設置緩存過時時間

說到前頭:通過一番測試,把域名解析到nginx 上了,網站訪問量比較大,nginx,按照下面的方法,我本覺得會很快,結果網站基本仍是打不開。 php

我以爲問題可能出在: html

一、nginx 所在服務器和 源服務器不是一個機房,不在同一個局域網中 linux

二、對linux 瞭解比較少,不知道哪裏配置錯誤了 nginx



通過不懈努力 反覆實驗,終於搞定了 nginx 緩存動態頁面的方法,和設置緩存過時的方法 ajax

需求: sql

公司服務器用的是 windows + IIS  + asp.net + ms sql  windows

網站訪問量比較大,若是直接用動態網站上去,基本打不開 centos

一、最先的時候網站使用的是 在服務器上寫程序,生成html ,讓用戶直接訪問html,雖然效果很好,可是程序難以維護 瀏覽器

每次生成要 好久好久,有時候 生成 html 的頁面會死掉,會斷開連接,服務器上面消耗的內存cpu 也比較大 緩存


二、再後來我本身寫了一個程序,把網站全部請求都 發送給該程序,該程序 去請求動態頁面內容,緩存到 本地,而後第二個用戶再去訪問的時候,去判斷 緩存文件是否過時(我設置30分鐘過時),若是沒過時就直接輸出該文件

程序在這裏:http://www.oschina.net/code/snippet_172400_10925

三、我把代碼貼出去以後,故意誇大其詞說大型網站靜態化方案,果真立刻有人來嗆我,說了一些我不知道 或者瞭解比較少的東西,nginx 和 proxy cache 而後就google baidu 瘋狂的找資料,以前接觸 linux 也比較少,恰好微軟查版權,致使公司大部分服務器換爲 linux,圖片服務器也要換成linux,我藉助此機會 去接觸 linux,並配置了 圖片服務器,用 nginx 反向代理把  源圖片服務器上的圖片緩存到 nginx 下,果真很方便

方案在這裏:http://my.oschina.net/foxidea/blog/90787


四、圖片服務器配置完成以後,就一直想 用nginx 去緩存咱們的動態網站頁面,可是有幾個問題:

動態網站和圖片服務器不同,動態網站要每過幾個小時從新生成一次緩存,有ajax 交互等是實時的

而圖片服務器 只要緩存下來就不用再去管了,圖片也不會變化

因此又通過一番波折 ,最後仍是高成功了:

這裏用虛擬機配置了下:

nginx 配置文件內容:

主要是這一句:

proxy_cache_path /www/ levels=1:2 keys_zone=Z:10m inactive=1m max_size=30g;

這一句定義一個區域,名字是 Z ,在內存中的空間爲10MB ,硬盤中的最大空間爲 30G;

 inactive=1m   是,1分鐘以後緩存失效 ,重新從源服務器請求

這裏糾正一下,inactive=1m  若是緩存1分鐘沒人訪問,nginx 會刪除掉這些緩存

/usr/local/nginx/conf/nginx.conf

#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;
    proxy_cache_path /www/ levels=1:2 keys_zone=Z:10m inactive=1m max_size=30g;
    server {
        listen       80;
        server_name  localhost;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

        location / {
            root   /www/;
	    #expires max;

            #proxy_store on;
            #proxy_store_access user:rw group:rw all:rw;
            #proxy_temp_path /www/;
	    proxy_cache Z;
	    proxy_cache_valid 200 1m;
            #expires max;
            include proxy.conf;
	
            if ( !-e $request_filename) {
            proxy_pass  http://192.168.1.199:45815;
            }
        }
#這裏設置當 訪問 /ajax/目錄下的內容時候,直接從源服務器讀取,主要用於ajax 的訪問請求,要求實時的
        location /ajax/ {

            include proxy.conf;
            if ( !-e $request_filename) {
            proxy_pass  http://192.168.1.199:45815;
            }
        }

        #location ~.*\.(jpg|png|jpeg|gif)
        #{
	#    expires max;
        #}

        #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;
    #    server_name  localhost;

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

    #    ssl_session_timeout  5m;

    #    ssl_protocols  SSLv2 SSLv3 TLSv1;
    #    ssl_ciphers  HIGH:!aNULL:!MD5;
    #    ssl_prefer_server_ciphers   on;

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

}


/usr/local/nginx/conf/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;
proxy_set_header        Accept-Encoding 'gzip';
client_max_body_size    100m;
client_body_buffer_size 256k;

proxy_connect_timeout   60;
proxy_send_timeout      60;
proxy_read_timeout      60;

proxy_buffer_size       512k;
proxy_buffers           8 512k;
proxy_busy_buffers_size 512k;
proxy_temp_file_write_size 512k;



一開始我就這樣配置,認爲能夠成功了,結果發現動態文件沒法被緩存,而html 文件能夠被緩存,後來就到不少地方去問,

心想會不會是由於 文件 的 頭信息或者Last-Modified 信息和 ETag 形成的,就去問,http://www.dewen.org/q/9769/nginx+%E5%A6%82%E4%BD%95%E7%BC%93%E5%AD%98%E5%8A%A8%E6%80%81%E9%A1%B5%E9%9D%A2%EF%BC%9F

發現果然如此,立刻修改源服務器的動態文件,加入如下代碼:

<%@ Page Language="C#" %>
<% 
    
    
    string date = Request.Headers.Get("If-Modified-Since");
    if (date != null)
    {
        Response.StatusCode = 304;
        Response.StatusDescription = "from cache";
        return;
    }

    DateTime expDate = new DateTime(2037, 12, 31, 23, 55, 55);
    Response.Cache.SetCacheability(HttpCacheability.Public);
    Response.Cache.SetExpires(expDate);
    Response.Cache.SetMaxAge(expDate - DateTime.Now);
    Response.Cache.SetLastModified(new DateTime(2000, 1, 1));


    
%>

<%=DateTime.Now.ToString()%>

而後發現就能夠緩存動態文件了。至此,下一步我就能夠用nginx 做爲用戶訪問的 服務器了

這裏截一些圖:


源服務器  http://192.168.1.199:45815/ajax/r.aspx


源服務器  http://192.168.1.199:45815/d.aspx





源服務器  http://192.168.1.199:45815/default.html




虛擬機中 nginx 的域名是 localhost 

經過虛擬機centos 瀏覽器 firefox 分別去訪問 

localhost/d.aspx

localhost/ajax/r.aspx

localhost/default.html

不停刷新(ctrl+f5) 看頁面變化



訪問:localhost/default.html  刷新始終沒有變化,手工去修改 源服務器  http://192.168.1.199:45815/default.html  ,發現一分鐘以後,會變化









訪問:localhost/ajax/r.aspx 刷新始終是變化的,顯示當前的時間

訪問:localhost/d.aspx 刷新 ,和 localhost/default.html 效果同樣,一分鐘以後纔會變化





#通過測試,上面的方法好像不行,彷佛永久緩存了

修改下動態頁面的代碼:


<%@ Page Language="C#" %>
<script runat="server">
    void EchoCachePageHeader()
    {
        DateTime expDate =  DateTime.Now.AddSeconds(60);//設置緩存60秒
        Response.Cache.SetCacheability(HttpCacheability.Public);
        Response.Cache.SetExpires(expDate);
        Response.Cache.SetMaxAge(expDate - DateTime.Now);
        
        
        Response.Cache.SetLastModified(DateTime.Now);
    }
</script>
<% 
    
   
    //If-Modified-Since:
    string date = Request.Headers.Get("If-Modified-Since");

    Response.Write(date);

    Response.Write("<br />");
    
    if (date != null)
    {

        try
        {
            DateTime ifDate = Convert.ToDateTime(date);

            if ((DateTime.Now - ifDate).TotalSeconds <= 60)
            {
                Response.StatusCode = 304;
                Response.StatusDescription = "from cache";
                return;
            }
            else
            {
                EchoCachePageHeader();
            }
        }
        catch
        {

            EchoCachePageHeader();        
        }

    }
    else
    {
        EchoCachePageHeader();
    }

    
    
%>
<br />
<%=DateTime.Now %>


裝了兩個瀏覽器測試了下緩存,是同樣的結果,這樣就很是好了



相關文章
相關標籤/搜索