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.

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?

share|improve this question
add comment

3 Answers

up vote 2 down vote accepted

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;
}
share|improve this answer
add comment

nginx will have to intercept Apache's response recognize the 404 versions, and return its own.

If nginx doesn't have a way to do that, then perhaps you could configure Apache to not return anything - thereby triggering nginx's own 404 state?

share|improve this answer
add comment

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.

share|improve this answer
add comment

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.