内容类型相关的nginx到期头

时间:2012-07-03 13:27:09

标签: nginx expires-header

是否可以在nginx中设置内容类型相关的expires头?我对nginx很新,并尝试了以下内容:

    location ~ /files\.php$ {
    ...
            if ($content_type = "text/css") {
                    add_header X-TEST1 123;
                    expires 7d;
            }
            if ($content_type = "image/png") {
                    add_header X-TEST2 123;
                    expires 30d;
            }
            if ($content_type = "application/javascript") {
                    add_header X-TEST3 123;
                    expires 1d;
            }
            #testing
            if ($content_type != "text/css") {
                    add_header X-TEST4 abc;
            }
            #testing
            if ($content_type = text/css) {
                    add_header X-TEST5 123;
            }
    }

但是在所有请求中添加的唯一标题是“X-TEST4”。 我知道使用文件扩展名的其他解决方案:

location ~* \.(ico|css|js|gif|jp?g|png)\?[0-9]+$

但它不适用于我的申请。

3 个答案:

答案 0 :(得分:0)

我认为代码应该在location / { }而不是location ~ /files\.php$ { } ...

答案 1 :(得分:0)

你试过吗

$content_type ~= application/javascript

另外,请务必阅读: http://wiki.nginx.org/IfIsEvil

答案 2 :(得分:0)

如果您安装了lua模块,则可以执行类似的操作:

server {

    location / {...}

    header_filter_by_lua_block {

            local cct = {}  -- # cached content types

            cct["text/css"] = true
            cct["application/javascript"] = true
            cct["application/x-javascript"] = true
            cct["text/javascript"] = true
            cct["image/jpeg"] = true
            cct["image/png"] = true
            cct["application/vnd.ms-fontobject"] = true
            cct["application/font-woff"] = true
            cct["application/x-font-truetype"] = true
            cct["image/svg+xml"] = true
            cct["application/x-font-opentype"] = true

            if cct[ngx.header.content_type] ~= nil and ngx.header["expires"] == nil then
                    local now = os.time()
                    local expires = os.date("%a, %d-%b-%Y %H:%I:%S GMT", now+604800) -- # one week in seconds

                    ngx.header["expires"] = expires
            end
    }
}

具有指定内容类型的响应现在将获得一个expires-header。 当响应已经有一个expires-header时,lua块将不会碰到该报头。

相关问题