Nginx rewriting files that do not exist

nginxrewrite

Nginx is returning the site root index instead of a 404 response for non-existent files, i.e. attempting to rewrite files that do not exist which is undesired. While I see the topic was answered here, I do not see how it applies to my configuration and thought using IF statements in Nginx is evil?

The object of this is to redirect /bar.html and /bar/ requests to /bar. The data being served are from bar.html. A request for /bar.random will return the sites /index.html content instead of a 404. A request for a file that does not exist should return a 404 error page.

root   /usr/share/nginx/html;
index  index.html;

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

rewrite ^(/.+)/$ $1 permanent;
rewrite ^(/.+)\.html$ $1 permanent;

location @extensionless-html {
    rewrite ^(.*)$ $1.html last;
}

I have also tried the following which resulted in the same reponse:

location / {
    try_files $uri $uri.html /index.html @extensionless-html =404;

if (-f $request_filename) {
    # redirect /foo/ to /foo
    rewrite ^(/.+)/$ $1 permanent;
    # redirect /foo.html to /foo
    rewrite ^(/.+)\.html$ $1 permanent;
}
}

location @extensionless-html {
    rewrite ^(.*)$ $1.html last;
}

Best Answer

Based on feedback, removing index.html from try_files allows 404 errors to work as desired.

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

# redirect /foo/ to /foo
rewrite ^(/.+)/$ $1 permanent;
# redirect /foo.html to /foo but
rewrite ^(/.+)\.html$ $1 permanent;

location @extensionless-html {
    rewrite ^(.*)$ $1.html last;
}