How can i do a redirect with 404 as status code in Nginx [closed]

You can’t. 404 isn’t a redirect status code, it’s an error status code, and so web browsers that receive it will treat it as an error rather than a redirect. If you want to say that the page isn’t there any more and send the browser to find it somewhere else, that’s what the 301 code is for.


You cannot control the HTTP status code of an external page.

However, if what you want to achieve is displaying external page's content with 404 status on your site, this is totally possible. You can use proxy_pass.

But it gets more tricky if the remote location emits 200. Two locations would be needed:

location = /foo {
    error_page 404 = @ext_404;
    return 404;
}

location @ext_404 {
    proxy_pass https://bar.example.com;
    rewrite .* /lorem-ipsum break;

    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header Host bar.example.com;
    proxy_set_header X-NginX-Proxy true;
    proxy_redirect off;
    proxy_connect_timeout 1;
    proxy_intercept_errors off;
    expires 30;
}

As a result, when someone visits https://your.example.com/foo, they will actually see the contents of https://bar.example.com/lorem-ipsum with 404 status code.


A 404 can be done only internally it can't be done for an external URL. You can only direct it but not with a 404. A 404 means that it's not there or dosen't exists.

If both servers or urls belongs to you, you can redirect to a php page with a php header of 404 and a refresh html meta that would redirect to the new URL. But this is not the right way to redirect