3

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!

Zak
  • 1,910
  • 3
  • 16
  • 31

1 Answers1

6

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;
    }
}
DMCoding
  • 1,167
  • 2
  • 15
  • 30
  • Though I'm not sure of the purpose of specifying the root directory /usr/share/nginx/html; if you are using proxy_pass... – DMCoding Jan 20 '16 at 03:15