目录:
- 1、如何在nginx中缓存静态文件
- 2、【NGINX入门】3.Nginx的缓存服务器proxy_cache配置
- 3、nginx 反代里缓存怎么清理
- 4、缓存静态资源,不知怎么解决
- 5、如何在Nginx中缓存静态文件,为访问站点提速
如何在nginx中缓存静态文件
首先确定配置文件httpd.conf中确已经加载mod_headers模块。LoadModuleheaders_modulemodules/mod_headers.so我们可以根据文件类型来让浏览器每次都从服务器读取,这里测试用css、js、swf、php、html、htm这几种文件。HeadersetCache-Control"private,no-cache,no-store,proxy-revalidate,no-transform"HeadersetPragma"no-cache"
【NGINX入门】3.Nginx的缓存服务器proxy_cache配置
本文介绍NGINX缓存机制,配置和参数说明。
如图所示,nginx缓存,可以在一定程度上,减少源服务器的处理请求压力。因为静态文件(比如css,js, 图片)中,很多都是不经常更新的。nginx使用proxy_cache将用户的请求缓存到本地一个目录。下一个相同请求可以直接调取缓存文件,就不用去请求服务器了。毕竟,IO密集型服务的处理是nginx的强项。
Nginx的缓存加速功能是由proxy_cache(用于反向代理和静态缓存)和fastcgi_cache(PHP动态缓存)两个功能模块完成。
Nginx缓存特点:
先上个例子:
因为我是在一台服务器上做试验,所以用了两个端口 80 和 90 进行模拟两台服务器之间的交互。
接下来讲一下配置项:
这里我设置了 图片 、 css 、 js 静态资源进行缓存。
当用户输入 域名时,解析得到 ip:port 的访问地址。 port 默认为80。所以页面请求会被当前server截取到,进行请求处理。
当解析到上述文件名结尾的静态资源,会到缓存区获取静态资源。
如果获取到对应资源,则直接返回数据。
如果获取不到,则将请求转发给 proxy_pass 指向的地址进行处理。
这里直接处理 90 端口接受到的请求,到服务器本地目录 /mnt/blog 下抓取资源进行响应。
细心的读者应该发现,我在第二段例子里,留了个彩蛋 add_header wall "hey!guys!give me a star." 。
add_header 是用于在报头设置自定义的信息。
所以,如果缓存有效的话,那么静态资源返回的报头,一定会带上这个信息。
(1)Nginx系列教程(3)nginx缓存服务器上的静态文件
(2)proxy_cache
nginx 反向代理之 proxy_cache
(3)Nginx使用upstream负载均衡和proxy_cache缓存实现反向代理
nginx 反代里缓存怎么清理
最简单的反代+全缓存脚本:
#新建2个目录,放置缓存文件:
mkdir -p /home/cache/path
mkdir /home/cache/temp
修改/usr/local/nginx/conf/nginx.conf的http层,添加以下代码:
client_body_buffer_size 512k;
proxy_connect_timeout 5;
proxy_read_timeout 60;
proxy_send_timeout 5;
proxy_buffer_size 16k;
proxy_buffers 4 64k;
proxy_busy_buffers_size 128k;
proxy_temp_file_write_size 128k;
proxy_temp_path /home/cache/temp;
proxy_cache_path /home/cache/path levels=1:2 keys_zone=cache_one:10m inactive=7d max_size=30g;
#500m是内存占用,7d是7天无访问删除,30g是缓存占具硬盘空间
#limit_zone crawler $binary_remote_addr 10m; #这段是用于限制单ip连接数的,如果频繁出现后端负载过大可以尝试去掉#。
扩展资料:
nginx仅仅处理静态页面,动态的页面(php请求)统统都交付给后台的两台apache来处理。也就是说,可以把网站的静态页面或者文件放置到nginx的目录下;动态的页面和数据库访问都保留到后台的apache服务器上。
假设前端nginx(为127.0.0.1:8080)仅仅包含一个静态页面index.html;后 台的两个apache服务器(分别为localhost:80和158.37.70.143:80),一台根目录放置phpMyAdmin文件夹和 test.php(里面测试代码为print "server1";),另一台根目录仅仅放置一个test.php(里面测试代码为print "server2";)。
参考资料来源:百度百科-反向代理负载平衡
缓存静态资源,不知怎么解决
之前看过apach及nginx对于静态资源(含js,图片,css等)部分的缓存,用于加速并减轻后台实际web服务器的压力。
静态资源缓存是WEB服务器优化的一种手段,基本原理如下:
1.客户端浏览器请求服务器一个服务(该服务含有图片,js等静态资源),通常会对于每一个网页中的独立图片或js文件发送一个http请求
2.WEB服务器对于每个资源HTTP请求进行解析,并生成一个资源修改时间的唯一值(可以是etag或last_modified参数),放入服务器端map,key为资源url,value为资源修改时间。最后将此资源修改时间的唯一值包含在http头上返回,因为是首次请求,所以会将所有内容放在http body中一并返回给客户浏览器端
3.客户浏览器接收服服务器响应,并将服务器返回的资源修改时间作为key放入浏览器客户端,value为http body中的实际资源内容
4.客户浏览器再次请求静态资源时,会将资源修改时间一并发送给服务器
5.服务端会从最新的map中取出该资源url对应的修改时间,如果值晚于客户端请求的资源修改时间,这时会返回最新的已经修改过的资源给客户端。否则返回304 not modifed
这里记录资源修改时间的方式有etag及last_modified。最先有的是last_modified,它的工作方式就是上述介绍的,但缺点是只能精确到秒级别。也就是说当你在一秒中修改资源两次,而客户端拿到的是第一次修改,那之后就算客户端第二次再次请求也不会拿到最新的资源。
而etag的出现正是为了解决last_modified的秒级问题,于http 1.1被提出。
今天测试了下,在没有nginx等前端反向代理服务器时,tomcat竟然默认对静态资源做了缓存。
tomcat默认运用etag及last_modifed。etag与if_no_match(客户端浏览器上传时在http head中应该放的属性名)一起使用,last_modified与If-Modified-Since一起使用。
客户端首次请求时,得到请求响应数据如下:
GET [HTTP/1.1 200 OK 1ms]
GET [HTTP/1.1 200 OK 1ms]
GET [HTTP/1.1 200 OK 2ms]
我们看一下Hello.js这个请求响应具体信息:
server Apache-Coyote/1.1 (表明服务器是tomcat)
Last-Modified: Sun, 11 May 2014 10:54:33 GMT
Etag: W/"175-1399805673000"
Date: Sun, 11 May 2014 10:59:23 GMT
Content-Type: application/javascript;charset=UTF-8
Content-Length: 175
Accept-Ranges: bytes
从上面可以看到tomcat即返回了last_modified也返回了etag。
客户端再次请求时,请求数据如下:
If-None-Match: W/"175-1399805673000"
If-Modified-Since: Sun, 11 May 2014 10:54:33 GMT
响应如下:
GET [HTTP/1.1 200 OK 1ms]
GET [HTTP/1.1 304 Not Modified 1ms]
GET [HTTP/1.1 304 Not Modified 1ms]
从中我们可以看到tomcat对于静态数据作了缓存。
接着我们分析tomcat对于这部分静态缓存的判断处理,这部分逻辑是写在DefaultServlet类中,
我们可以在doGet方法中进入ServiceContext方法中找到以下源码:
// Check if the conditions specified in the optional If headers are
// satisfied.
if (cacheEntry.context == null) {
// Checking If headers
boolean included =
(request.getAttribute(Globals.INCLUDE_CONTEXT_PATH_ATTR) != null);
if (!included
!checkIfHeaders(request, response, cacheEntry.attributes)) { //这句判断是否需要返回整个资源请求
return;
}
}
上面源码的 if (!included
!checkIfHeaders(request, response, cacheEntry.attributes))
用于判断是否需要返回整个资源,如果indcluded与checkIfHeaders方法返回的都是false,这时就直接返回,说明资源未修改,或者是缓存不支持的请求方式。
我们接着查看checkIfHeaders方法:
/**
* Check if the conditions specified in the optional If headers are
* satisfied.
*
* @param request The servlet request we are processing
* @param response The servlet response we are creating
* @param resourceAttributes The resource information
* @return boolean true if the resource meets all the specified conditions,
* and false if any of the conditions is not satisfied, in which case
* request processing is stopped
*/
protected boolean checkIfHeaders(HttpServletRequest request,
HttpServletResponse response,
ResourceAttributes resourceAttributes)
throws IOException {
return checkIfMatch(request, response, resourceAttributes)
checkIfModifiedSince(request, response, resourceAttributes)
checkIfNoneMatch(request, response, resourceAttributes)
checkIfUnmodifiedSince(request, response, resourceAttributes);
}
可以看到tomcat只有当这四个属性全部返回true(也就是说全部认为资源已经改变)才会返回true,这样最终会将整个资源(最新修改过的)返回客户端。
在这里,我们从上面实际过程当中看到,浏览器第二次请求资源时在http请求header中放了
If-None-Match: W/"175-1399805673000"
If-Modified-Since: Sun, 11 May 2014 10:54:33 GMT
这两个属性。
因此我们查看
checkIfModifiedSince(request, response, resourceAttributes)
checkIfNoneMatch(request, response, resourceAttributes)
这两个方法
checkIfModifiedSince源码如下:
/**
* Check if the if-modified-since condition is satisfied.
*
* @param request The servlet request we are processing
* @param response The servlet response we are creating
* @param resourceInfo File object
* @return boolean true if the resource meets the specified condition,
* and false if the condition is not satisfied, in which case request
* processing is stopped
*/
protected boolean checkIfModifiedSince(HttpServletRequest request,
HttpServletResponse response,
ResourceAttributes resourceAttributes) {
try {
long headerValue = request.getDateHeader("If-Modified-Since");
long lastModified = resourceAttributes.getLastModified();
if (headerValue != -1) {
// If an If-None-Match header has been specified, if modified since
// is ignored.
if ((request.getHeader("If-None-Match") == null)
(lastModified headerValue + 1000)) {
// The entity has not been modified since the date
// specified by the client. This is not an error case.
response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
response.setHeader("ETag", resourceAttributes.getETag());
return false;
}
}
} catch (IllegalArgumentException illegalArgument) {
return true;
}
return true;
}
源码中可以看到:
if ((request.getHeader("If-None-Match") == null)
(lastModified headerValue + 1000)) {
这句话表明只有在客户端浏览器发送的请求头中不包含If-None-Match,IfModifiedSince才会生效。
我们接着看checkIfNoneMatch,源码如下:
/**
* Check if the if-none-match condition is satisfied.
*
* @param request The servlet request we are processing
* @param response The servlet response we are creating
* @param resourceInfo File object
* @return boolean true if the resource meets the specified condition,
* and false if the condition is not satisfied, in which case request
* processing is stopped
*/
protected boolean checkIfNoneMatch(HttpServletRequest request,
HttpServletResponse response,
ResourceAttributes resourceAttributes)
throws IOException {
String eTag = resourceAttributes.getETag();
String headerValue = request.getHeader("If-None-Match");
if (headerValue != null) {
boolean conditionSatisfied = false;
if (!headerValue.equals("*")) {
StringTokenizer commaTokenizer =
new StringTokenizer(headerValue, ",");
while (!conditionSatisfied commaTokenizer.hasMoreTokens()) {
String currentToken = commaTokenizer.nextToken();
if (currentToken.trim().equals(eTag))
conditionSatisfied = true;
}
} else {
conditionSatisfied = true;
}
if (conditionSatisfied) {
// For GET and HEAD, we should respond with
// 304 Not Modified.
// For every other method, 412 Precondition Failed is sent
// back.
if ( ("GET".equals(request.getMethod()))
|| ("HEAD".equals(request.getMethod())) ) {
response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
response.setHeader("ETag", eTag);
return false;
}
response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
return false;
}
}
return true;
}
这里:
String eTag = resourceAttributes.getETag();
String headerValue = request.getHeader("If-None-Match");
这两句比较简单,就是分别从服务器缓存和http请求头中中取出etag。
接着判断这两个etag如果相等,则conditionSatisfied为true,会执行到以下语句:
if (conditionSatisfied) {
// For GET and HEAD, we should respond with
// 304 Not Modified.
// For every other method, 412 Precondition Failed is sent
// back.
if ( ("GET".equals(request.getMethod()))
|| ("HEAD".equals(request.getMethod())) ) {
response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
response.setHeader("ETag", eTag);
return false;
}
response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
return false;
}
这段语句中可以发现,如果资源未改变的情况下,并且请求方式为GET或者HEAD时,会返回304状态码。否则返回一个412状态码,同样不会返回资源内容。
如果上述最终
if ((request.getHeader("If-None-Match") == null)
(lastModified headerValue + 1000))
条件不成立,即资源更新了或者是第一次请求,这里会读取当前请求资源文件,并最终放入http响应中。
如何在Nginx中缓存静态文件,为访问站点提速
采用缓存技术可以提高网站公开的响应速度,但在一定程度上也降低了服务器的负载。 相比静态网页与动态网页,它不要求服务器端计算,所以在页面打开的响应速度为比动态页面更快! 虽然我不太懂,但是如果你掩盖了服务器上的静态页面。
评论前必须登录!
注册