如何知道何时发送304 Not Modified响应 [英] How to know when to send a 304 Not Modified response

查看:114
本文介绍了如何知道何时发送304 Not Modified响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一种资源处理方法,用于控制对各种文件的访问,我希望能够使用浏览器的缓存。我的问题有两个:

I'm writing a resource handling method where I control access to various files, and I'd like to be able to make use of the browser's cache. My question is two-fold:


  1. 我需要检查哪些权威的HTTP标头,以确定是否我应该发送一个304响应,当我检查它时我在寻找什么?

  1. Which are the definitive HTTP headers that I need to check in order to know for sure whether I should send a 304 response, and what am I looking for when I do check them?

此外,我还需要发送任何标题最初发送文件(如'Last-Modified')为200响应?

Additionally, are there any headers that I need to send when I initially send the file (like 'Last-Modified') as a 200 response?

有些伪代码可能会是最有用的答案。

Some psuedo-code would probably be the most useful answer.

缓存控制标题怎么样?可能的各种可能值会影响您发送给客户端的内容(即max-age),还是应该只有在被修改后才能遵守?

What about the cache-control header? Can the various possible values of that affect what you send to the client (namely max-age) or should only if-modified-since be obeyed?

推荐答案

这是我实现它的方式。代码已经工作了一年多,并且有多个浏览器,所以我认为它非常可靠。这是基于 RFC 2616 并观察各种浏览器的内容和时间正在发送。

Here's how I implemented it. The code has been working for a bit more than a year and with multiple browsers, so I think it's pretty reliable. This is based on RFC 2616 and by observing what and when the various browsers were sending.

这是伪代码:


server_etag = gen_etag_for_this_file(myfile)
etag_from_browser = get_header("Etag")

if etag_from_browser does not exist:
    etag_from_browser = get_header("If-None-Match")
if the browser has quoted the etag:
    strip the quotes (e.g. "foo" --> foo)

set server_etag into http header

if etag_from_browser matches server_etag
    send 304 return code to browser

这是我的服务器逻辑片段,用于处理此事。

Here's a snippet of my server logic that handles this.


/* the client should set either Etag or If-None-Match */
/* some clients quote the parm, strip quotes if so    */
mketag(etag, &sb);

etagin = apr_table_get(r->headers_in, "Etag");
if (etagin == NULL)
    etagin = apr_table_get(r->headers_in, "If-None-Match");
if (etag != NULL && etag[0] == '"') {
    int sl; 
    sl = strlen(etag);
    memmove(etag, etag+1, sl+1);
    etag[sl-2] = 0;
    logit(2,"etag=:%s:",etag);
}   
... 
apr_table_add(r->headers_out, "ETag", etag);
... 
if (etagin != NULL && strcmp(etagin, etag) == 0) {
    /* if the etag matches, we return a 304 */
    rc = HTTP_NOT_MODIFIED;
}   

如果你想在etag生成方面获得一些帮助,可以发布另一个问题,我也会挖出一些代码来解决这个问题.HPH!

If you want some help with etag generation post another question and I'll dig out some code that does that as well. HTH!

这篇关于如何知道何时发送304 Not Modified响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆