nginx过期标头和反向代理无法正常工作

时间:2013-03-09 13:27:03

标签: nginx reverse-proxy expires-header

我正在尝试为nginx(0.7.67)上的静态文件配置Expires头。静态文件由Golang反向代理提供:

location /rev/ {
  proxy_pass http://localhost:8910/;
  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  X-Forwarded-Proto  https;

  # I am putting this here, because nginx only uses one location. Is this OK?
  location ~* \.(js|css|jpg|jpeg|gif|png|svg|ico|pdf|html|htm)$ {
    expires 30d;
  }
}

当我这样做时,重启nginx没有错误,但静态文件不再提供。

已经尝试以下星座,但它不起作用:

server {
  ...
  location /rev/ {
    proxy_pass http://localhost:8910/;
    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  X-Forwarded-Proto  https;
  }

  location ~* \.(js|css|jpg|jpeg|gif|png|svg|ico|pdf|html|htm)$ {
      expires 30d;
  }
}

问题:如何为反向代理后面的应用程序上的静态文件应用expires头?

3 个答案:

答案 0 :(得分:7)

我设法完成它的唯一方法就是这样:

location / {
    proxy_pass  http://tomcat;
}

# CACHING WITH NO LOGGING
location ~* ^.+\.(atom|bmp|bz2|doc|docx|eot|exe|gif|gz|ico|jpeg|jpg|mid|midi|mp4|ogg|ogv|otf|pdf|png|ppt|pptx|rar|rss|rtf|svg|svgz|swf|tar|tgz|ttf|txt|wav|woff|xls|zip)$ {
    access_log  off;
    log_not_found   off;
    expires     max;
    proxy_pass  http://tomcat;
}

# CACHING WITH 404 LOGGING
location ~* ^.+\.(css|js|xml)$ {
    access_log  off;
    log_not_found   on;
    expires     max;
    proxy_pass  http://tomcat;
}

希望它有所帮助!

答案 1 :(得分:1)

通过阅读http://wiki.nginx.org/HttpProxyModule处的文档,我发现使用proxy_cache_*指令来实现类似的功能,尽管不完全是你所追求的。文档声明:

Upstream cache-related directives have priority over proxy_cache_valid value,
in particular the order is:

X-Accel-Expires
Expires/Cache-Control
proxy_cache_valid

因此,似乎不支持或建议在代理级别设置Expires标头。

我觉得你应该设置Expires标题上游。这可以通过在http处理程序函数中的http.ResponseWriter上设置标头,在Go中完成(稍微有点hackishly,我确信有更好的方法来修复字符串中的时区):

w.Header().Set("Expires", strings.Replace(time.Now().AddDate(0, 0, 30).Format(time.RFC1123), "UTC", "GMT", 1))

如前所述,这会在输出字符串中用UTC替换GMT。我不确定是否有必要,但我注意到这似乎是我检查的任何HTTP头中的常见形式。我没有查看规范,看看浏览器是否会同等地接受UTC,但我不明白为什么不这样做。

很抱歉,这不是Nginx的答案,希望它有所帮助!

答案 2 :(得分:0)

我认为expires指令或add_header是您返回浏览器的内容。

如果您盲目想要缓存来自后端的内容,可以尝试:

proxy_cache_valid any 1m;

http://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_cache_valid

相关问题