3

Coming from an Apache background, in the past I have hidden .html file extensions using a pair of rewrite rules:

RewriteCond %{THE_REQUEST} ^(GET|HEAD)\ /.+\.html\ HTTP
RewriteRule ^(.+)\.html$ http://%{HTTP_HOST}/$1 [R=301,L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME}.html -f
RewriteRule ^.+$ %{REQUEST_FILENAME}.html [L]

nginx's rewriting capabilities are different, a possible solution lies here however, the nginx wiki suggests that if at all possible avoiding ifs is the best solution, and discusses using (try_files) instead. I was wondering whether anyone had the best way to implement something like this, as whilst:

try_files $uri $uri.html =404;

works in some cases, you would get massive redirect problems etc. Is there any way to avoid ifs in this case?

jvc26
  • 6,363
  • 6
  • 46
  • 75

1 Answers1

1

You would use the try_files directive like so:

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

this does the following for each uri that matches the location block

  1. check if there's an exact match file, if so serve it
  2. if no exact match was found, then try adding .html to the request
  3. if that wasn't found either return a 404

there's no redirecting at all in that, just nginx checking several options in turn.

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME}.html -f
RewriteRule ^.+$ %{REQUEST_FILENAME}.html [L]

the first 2 lines of that are basically 1. and 2. except that nginx doesn't need to rewrite the url as the try_files directive makes it smart enough to just return the request when the match is found

cobaco
  • 10,224
  • 6
  • 36
  • 33