Nginx 404 page behavior

apache-2.2http-status-code-404nginxPROXY

I have the following nginx server config:

server {
    listen 80;
    server_name example.com
    root   /server/root;

    index index.php;

    error_page 404 = /index.php;

    location ~ \.php$ {
        try_files $uri =404;

        proxy_pass         http://127.0.0.1:8080;
        proxy_redirect     off;
        proxy_set_header   Host $host;
        proxy_set_header   X-Real-IP        $remote_addr;
        proxy_set_header   X-Forwarded-For  $proxy_add_x_forwarded_for;
        proxy_set_header   X-Request-URI    $request_uri;
    }

}

The behavior that I want is that when nginx encounters a request for a file which does not exist it instead shows the index.php page by way of a 404 page. The problem is it seems that apache (which is what's being proxied back to) is still trying to resolve the original request when it gets the request. If I go to http://example.com/blahblah, I get back the error:

The requested URL /blahblah was not found on this server.

Which is an apache error. How can I make it so that index.php is shown as the 404 page just the same as if it was a static file?

Best Answer

Which version of nginx are you using? This issue was addressed in 1.1.12: http://nginx.org/en/CHANGES

EDIT: If you can't update, you can replace your current error_page and try_files with:

location / {
  try_files $uri $uri /index.php;
}

location ~ \.php$ {
  # Leave the =404 at the end so we don't 500 when /index.php doesn't exist
  try_files $uri /index.php =404;

  proxy_pass         http://127.0.0.1:8080;
  proxy_redirect     off;
  proxy_set_header   Host $host;
  proxy_set_header   X-Real-IP        $remote_addr;
  proxy_set_header   X-Forwarded-For  $proxy_add_x_forwarded_for;
  proxy_set_header   X-Request-URI    $request_uri;
}
Related Topic