Nginx send 404 to backend

Written by
Date: 2015-05-24 18:05:32 00:00

Spanish

How to make Nginx forward requirements to backend when an error 404 “file not found”

Nginx is a great web server, but it is also great as a reverse proxy, and guess what, it is great when doing both things at once.

If you want to make Nginx act as a web server, but if there is an error a 404 error you can pass the call back to Apache or any other backend.

    location / {
        index index.html
        try_files $uri $uri/ @apache;
    }

That will tell Nginx to serve all pages and folders that match with a file or folder in the disk, but if it can’t find it, it will forward to @apache

And @apache looks like this:

    location @apache {
		proxy_pass http://1.2.3.4:81;
		proxy_redirect off;
		proxy_set_header Host $host;
		proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
	}

Just change the IP and port in the proxy_pass directive to match your requirement.

Edit: May 28, I have found that in order to be sure that Nginx will send all “File Not Found 404” errors to backend you need to also add this line to the server block.

error_page   404  = @apache;

The final block might look like this:

server {
	listen 80;
	root /var/www;
	index index.html;
	server_name www.garron.me;
	error_page   404  = @apache;
	location / {
		try_files $uri $uri/ @apache;
	}
	location @apache {
		proxy_pass http://localhost:8080;
		proxy_redirect off;
		proxy_set_header Host $host;
		proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
                proxy_cache wwwgarron;
                proxy_cache_valid 200 301 302 5s;
                proxy_cache_use_stale updating error timeout invalid_header http_500;
                proxy_ignore_headers Cache-Control Expires;
	}
}