为Nodejs应用使用代理缓存加速

不要使用Nodejs服务静态内容

Don't use nodejs for static content" @trevnorris. If #nginx isn't sitting in front of your node server, you're probably doing it wrong.— Bryan Hughes August 30, 2014">@nebrius

为什么要使用缓存?

缓存可以减少请求到上游服务器,可以提高站点的速度,Nginx是非常好的静态内容服务器,可以让Nginx服务静态内容,这意味着不会使用Node服务静态内容,可以把这些任务交给Nginx或者Apache,比如你的静态内容存储在

/var/www/example.com/htdocs/assets/. 

添加配置:

/etc/nginx/site-available/example.com

location /assets {  
     alias /var/www/example.com/htdocs/assets; access_log off; 
     expires max; 
 }

并不只是这些,如果数据没有改变,就可以代理缓存,因此我们需要生成新的html资源提供使用,Nginx将会存储Node的响应,响应返回的是静态内容,Nginx将会缓存这些响应,减少访问Node app次数

 proxy_cache_path /var/cache/nginx/exmaple.com 
 levels=1:2 
 keys_zone=ExampleSTATIC:100m 
 inactive=24h max_size=2g; 

 proxy_cache ExampleSTATIC;  
 proxy_cache_valid 200 10m; 
 proxy_cache_valid any 30s; 

你必须确保代理缓存路径已经存在

$ mkdir -p /var/cache/nginx/ 

测试Nginx配置,nginx -t 如果没有错误的消息

nginx: the configuration file /etc/nginx/nginx.conf syntax is ok nginx:  
configuration file /etc/nginx/nginx.conf test is successful 

*Full configuration *
upstream nodeapp {  
   server 127.0.0.1:port; 
} 

proxy_cache_path /var/cache/nginx/example.com  
levels=1:2  
keys_zone=ExampleSTATIC:75m  
inactive=24h  
max_size=512m;  

server {  
   server_name example.com;
   access_log /var/log/nginx/example.com.access.log; 
   error_log /var/log/nginx/example.com.error.log; 
   add_header X-Cache $upstream_cache_status;
   location / { 
        proxy_cache ExampleSTATIC;
        proxy_cache_valid 200 30m; 
        proxy_cache_valid 404 1m; 
        proxy_pass http://nodeapp; 
        proxy_ignore_headers X-Accel-Expires Expires Cache-Control;
        proxy_ignore_headers Set-Cookie;
        proxy_hide_header Set-Cookie; 
        proxy_hide_header X-powered-by; 
  } 
  location /assets/ { 
     alias /var/www/example.com/htdocs/assets/;
     access_log off; 
     expires max; 
  }  
}

最后重载Nginx

service nginx reload  
你的欣赏是我最大的动力

Yanxiong Huang

My name is Yanxiong Huang. graduated from Nanyang middle school.Love Linux,familiar with Node.js,Docker,Serverless... and more Web technology.Contact Me:QQ 31356617;Email:huangaynxiong2013@gmail.com

guangzhou,china http://www.myfreax.com

乐在分享