Hacker
Hacker

Reputation: 7906

redirect from one folder into another using nginx

I am running any Nginx file server. I have 2 main folders i.e. folder-a and folder-b. If a user tries to land on /folder-a/abc and it's a 404, I should auto-redirect to another folder like /folder-b/abc. How do I set up such a rule in Nginx? My top folder names will always be hard-coded names like folder-a and folder-b.

Upvotes: 0

Views: 2324

Answers (1)

Ivan Shatsky
Ivan Shatsky

Reputation: 15687

As being said by @RichardSmith, if you want to look for a file in one of two locations, you can use try_files directive:

location ~ ^/folder-a(?<suffix>/.*) {
    try_files $uri $uri/ /folder-b$suffix /folder-b$suffix/ =404;
}

If you want to generate an HTTP redirect, you can use error_page directive with the additional named location:

location ~ ^/folder-a(?<suffix>/.*) {
    error_page 404 @redirect;
}

location @redirect {
    return 301 /folder-b$suffix;
}

If you have some additional configuration directives in your root location (location / { ... }), you should either duplicate them inside the location ~ ^/folder-a(?<suffix>/.*) { ... } or move them to the server context if there are no other locations where those directives should not be applied.

Upvotes: 1

Related Questions