Home > Back-end >  How to set Nginx 404 page not affecting other directory?
How to set Nginx 404 page not affecting other directory?

Time:09-17

I need to set these two Urls redirect to a custom 404 page: https://example.com/frontend/#/, https://example.com/frontend/

the Nginx config below works fine:

server{
    listen 80;
    server_name example.com;
    
    error_page 404 /404.html;
    
    location = /404.html {
    root /opt/app/nginx/html;
    internal;
    }
    
    location = /frontend/ {
    return 404;
    }
}

However this setting makes URLs with the same prefixes go to 404 as well, which is a pain in the ass! https://example.com/frontend/#/abc, https://example.com/frontend/#/123 all redirect to 404. I use exact matching (= modifier) for the 404 settings, why does it still affect others and how can I fix it? Thank you for any help! :D

Edited I found the reason thanks to the answers given down there! So the # sign is processed by the browser only, the browser never passes # to the server, that's why Nginx treats https://example.com/frontend/#/abc, https://example.com/frontend/#/123 all as https://example.com/frontend/. In this case, if I wanna set https://example.com/frontend/#/ to the 404 page, what I need to do is to create an index page under /frontend folder in the project, and put 404 content inside the index page, There's nothing Nginx could do with redirecting URL contains hash sign.

CodePudding user response:

You can't do that because the hash part isn't sent to the server. It's for client side processing only.

CodePudding user response:

Try using two location without the "/" in each.

 location = /frontend {
return 404; }
 location = /frontend/# {
return 404; }
  • Related