2

是否可以在 nginx 中设置依赖于内容类型的过期标头?我对 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]+$

但它不适用于我的应用程序。

4

3 回答 3

0

你有没有尝试过

$content_type ~= application/javascript

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

于 2012-07-20T16:13:44.137 回答
0

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

于 2012-07-03T13:38:50.337 回答
0

If you have the lua module installed you could do something similar like this:

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
    }
}

Responses with the specified content-type will now get an expires-header. When the response already has an expires-header the lua block will not touch the header.

于 2018-06-21T20:21:46.190 回答