Zak
Zak

Reputation: 2060

Nginx redirect reverse proxy 404

I have the following Nginx server block:

server {
    listen 80;
    listen [::]:80;
    server_name example.com;
    root /usr/share/nginx/html;

    location / {
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $remote_addr;
        proxy_pass http://localhost/page-1/;
    }
}

I would like that when the user gets a 404 error on example.com, the proxy_pass should change to direct to http://localhost/example-404/.

However, this server block and the one for http://localhost both have the same root so alternatively it could just point to /example-404/ internally, I'm not sure which is easier to do. Either way, I want the address in the browser's address bar to stay the same.

The reason I want this is that there will be a different 404 page if accessing the server from http://localhost directly. I would really appreciate anyone's thoughts on this!

Upvotes: 3

Views: 12792

Answers (1)

DMCoding
DMCoding

Reputation: 1237

You can use different vhosts to give different results depending on how the user is accessing the server. I'd imagine something like this might work:

server {
    listen 80;
    server_name example.com;
    root /usr/share/nginx/html;

    location / {
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $remote_addr;
        proxy_intercept_errors on;
        error_page 404 = @errors;
        proxy_pass http://localhost/page-1/;
    }
    location @errors {
        root /usr/share/nginx/errors/example.com.404.html;
    }
}

server {
    listen 80;
    server_name localhost;
    root /usr/share/nginx/html;

    location / {
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $remote_addr;
        proxy_intercept_errors on;
        error_page 404 = @errors;
        proxy_pass http://localhost/page-1/;
    }
    location @errors {
        root /usr/share/nginx/errors/localhost.404.html;
    }
}

Upvotes: 6

Related Questions