Handling index.html redirection on Jekyll sites under NGINX

Most NGINX configurations found online for the fantastic static site generator Jekyll, have the undesirable side effect that both / and /index.html serve the same page. This is an issue for SEO since search engines penalize having the same content under more than one URL.

The following rewrite rule instructs NGINX to issue an HTTP permanent redirect to avoid this issue:

if ($request_uri = /index.html) {
  return 301 /;
}

This is how it looks on a complete NGINX server block:

server {
    
  server_name example.com;
  root /var/www/example_com/_site;
  index index.html;

  # SSL options and other stuff...
  #
  # ...
  #

  error_page 404 /404.html;
  location = /404.html {
     internal;
  }

  if ($request_uri = /index.html) {
     return 301 /;
  }

  location / {
    try_files $uri $uri.html $uri/ $uri/index.html =404;
  }
}

You can test this with curl. Before applying the rule you can see how both / and /index.html return an HTTP 200 OK response (which is not desirable):

$ curl -I http://example.com/index.html
--- snip ---
HTTP/1.1 200 OK
--- end ---

However after applying the rule, NGINX returns a permanent redirect to / which is correct and the desired behavior:

$ curl -I http://example.com/index.html
--- snip ---
HTTP/1.1 301 Moved Permanently
...
Location: http://example.com/
--- end ---

Posted

in

,

by

Tags: