Search code examples
http-redirectnginxrouteshttp-status-code-301

NGINX Redirect all paths to a specific path


I have a main domain (example.com) and multiple domains (example.net, example1.info, example2.info) pointing to one location in NGINX configuration like so:

server {
    server_name example.com *.com *.net *.info;
    root /home/example.com/public;
}

And I want to redirect a specific path /login to example.com/login, how do I accomplish it? If I do

server {
    server_name example.com *.com *.net *.info;
    root /home/example.com/public;

    location = /login {
    return 301 https://example.com/login;
}

this work for all domains, except example.com/login because it keeps redirecting to itself.

What is the correct way of creating a redirections from a specific path on all sites to my chosen path?


Solution

  • The simplest logic to redirect from one site to another is to isolate the target site with its own server block. Common configuration can be imported into both server blocks by using an include statement.

    I would use a default server block rather than a long list of wild cards.

    Something like this:

    server {
        listen 80 default_server;
        listen 443 ssl default_server;
    
        include /path/to/common/config;
    
        location = /login {
            return 301 https://example.com/login;
        }
    }
    
    server {
        listen 443 ssl;
    
        server_name example.com;
    
        include /path/to/common/config;
    }
    

    See this document for details.