Take the 2-minute tour ×
Server Fault is a question and answer site for professional system and network administrators. It's 100% free, no registration required.

Here is my nginx config:

 server {

    # Running port
    listen 80;

    error_page 404 /404;

    # Settings to by-pass for static files
    location ^~ / {

        # Example:
        # root /full/path/to/application/static/file/dir;
        root /var/www;
        include /etc/nginx/mime.types;
        try_files $uri $uri/ @htmlext;
    }

    location ~ \.html$ {
        try_files $uri = 404;
     }

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

The intention is to show the page /404 when a 404 error occurs. However, I'm now getting a 500 Internal Server Error when I visit a nonexistent page. Why?

share|improve this question

3 Answers 3

Try replacing this:

try_files $uri = 404;

with:

try_files $uri =404;
share|improve this answer

I think your main problem is here : rewrite ^(.*)$ $1.html last; and the use of the last flag.

Here is what the doc says :

If these directives [rewrite] are put inside location, the last flag should be replaced by break, or otherwise nginx will make 10 cycles and return the 500 error

This is what we can see in the Logs. Here i've asked for fake.html which does not exists :

[debug] 3480#0: *1 http script var: "/fake.html.html.html.html.html.html"
[debug] 3480#0: *1 trying to use file: "/fake.html.html.html.html.html.html" "/var/www/fake.html.html.html.html.html.html"
[debug] 3480#0: *1 http script var: "/fake.html.html.html.html.html.html"
[debug] 3480#0: *1 trying to use dir: "/fake.html.html.html.html.html.html" "/var/www/fake.html.html.html.html.html.html"
[debug] 3480#0: *1 trying to use file: "@htmlext" "/var/www@htmlext"
[error] 3480#0: *1 rewrite or internal redirection cycle while redirect to named location "@htmlext"....
[debug] 3480#0: *1 http finalize request: 500, "/fake.html.html.html.html.html.html?" a:1, c:7
[debug] 3480#0: *1 http special response: 500, "/fake.html.html.html.html.html.html?"

Interesting ! ;)

So, replace your rewrite rule by : rewrite ^(.*)$ $1.html break;

Alternatively, you can return a 404 if none of the file exists in the try_files directive :

try_files $uri $uri/ @htmlext =404;

However, at this point, your custom 404 page should not work.

Here's what i suggest :

server {
    # Running port
    listen 80;

    error_page 404 /404.html;

    location ~^/404.html {
       root /var/www;
       internal;
    }

    # Your other stuff Here ......
}
share|improve this answer

A proper way to define 404 page:

error_page 404 /404.html;
location  /404.html {
    internal;
}
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.