Nginx 404 page behavior

Mediocre Gopher asked:

I have the following nginx server config:

server {
    listen 80;
    root   /server/root;

    index index.php;

    error_page 404 = /index.php;

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

        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, 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?

My answer:

If you insist on using Apache, you’ll have to set up Apache rewrite rules to send 404 errors to your application, rather than in nginx’s configuration.

View the full question and any other answers on Server Fault.

Creative Commons License
This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.