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

Nginx is a great web , but it is also great as a reverse , 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 or any other backend.

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

That will tell Nginx to serve all pages and folders that match with a file or in the , 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 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;
	 /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_ wwwgarron;
                proxy__valid 200 301 302 5s;
                proxy__use_stale updating error timeout invalid_header http_500;
                proxy_ignore_headers -Control Expires;
	}
}
Print Friendly, PDF & Email

Comments

comments

Bài viết liên quan