如何知道何时发送304 Not Modified响应

tag*_*s2k 11 language-agnostic http

我正在编写一种资源处理方法,我可以控制对各种文件的访问,我希望能够使用浏览器的缓存.我的问题是双重的:

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

  2. 另外,当我最初发送文件(如'Last-Modified')作为200响应时,是否需要发送任何标头?

一些伪代码可能是最有用的答案.


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

Mar*_*son 8

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

这是伪代码:

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

这是我的服务器逻辑片段,用于处理此问题.

/* 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生成方面获得一些帮助,可以发布另一个问题,我也会挖出一些代码来解决这个问题.HTH!