基于Accept头值的Nginx自动索引格式

ppcbkaq5  于 4个月前  发布在  Nginx
关注(0)|答案(1)|浏览(59)

我想根据请求中收到的Accept HTTP标头的值设置autoindex_format值(htmlxmljson)。
我试过用map来做,但是在启动Nginx的时候得到了emerg

nginx: [emerg] invalid value "$autoindex_type" in /etc/nginx/nginx.conf

个字符
有没有人能建议一下,根据Nginx中HTTP请求的Accept值,如何正确设置autoindex_format的值?
谢谢你,谢谢

snz8szmq

snz8szmq1#

许多Nginx指令不接受变量作为参数。那些接受的指令应该明确地提到它。
有一种方法。您需要将每个autoindex_format语句放在自己的location块中。这三个location块将使用 fake URL,然后使用alias将它们转换为正确的路径名。
举例来说:

map $http_accept $autoindex_type {
    default html;
    ~json   json;
    ~xml    xml;
}

server {
    ...

    location / {
        rewrite ^ /$autoindex_type$uri last;
    }
    location /html/ {
            alias /usr/share/nginx/files/;
            autoindex on;
            autoindex_format html;
    }
    location /json/ {
            alias /usr/share/nginx/files/;
            autoindex on;
            autoindex_format json;
    }
    location /xml/ {
            alias /usr/share/nginx/files/;
            autoindex on;
            autoindex_format xml;
    }
}

字符串
在上面的示例中,fake URL使用前缀/html//json//xml/-但您可能希望对它们进行模糊处理,以避免与系统中的真实的URL发生潜在冲突。
我知道你已经接受了上面的答案,但我想添加第二个例子,它使用 named locations 而不是 fake URL,因此也避免了使用alias。它使用Nginx的一个(未记录的)功能,允许在变量中指定命名位置。
举例来说:

map $http_accept $autoindex_type {
    default @html;
    ~json   @json;
    ~xml    @xml;
}

server {
    ...

    root /usr/share/nginx/files;

    location / {
        try_files $uri $autoindex_type;
    }
    location @html {
            autoindex on;
            autoindex_format html;
    }
    location @json {
            autoindex on;
            autoindex_format json;
    }
    location @xml {
            autoindex on;
            autoindex_format xml;
    }
}


try_files至少需要两个参数,命名位置必须是最后一个参数。在示例中,$uri用作第一个参数。要防止try_files执行其 file 操作,请指定 fake 文件名,例如try_files nonexistent $autoindex_type;

相关问题