diary.sorah.jp

nginx: autoindex_format json; も使いたいが、html でも見たい

autoindex_format は if 使えないので、例によって rewrite で捻じ曲げると良い。

server {
  # ...
  autoindex on;
  root /foo/bar;
  charset utf-8;

  location / {
    if ( $http_accept = "application/json" ) {
      rewrite ^/(.*)$ /_indexjson/$1;
    }
    autoindex_format html;
  }

  location /_indexjson/ {
    internal;
    rewrite ^/_indexjson/(.*)$ /$1 break;
    autoindex_format json;
  }
  # ...
}

この例では Accept: application/json ヘッダの時に JSON を返すようになります。

Published at