Search code examples
linuxhttp-redirectnginxwebhttp-status-code-301

nginx redirect 301 all pages to another domain / homepage add query string


I ask for help because I have already broken my head, I do not know how to solve the problem ...

I move from one domain to another domain, I want all links 301 redirect to to the new domain, but to the home page I want to add query string like ?from=example.com (only for homepage).

https://example.com 301 -> https://newdomain.com/?from=example.com

all other links are just redirect 301 like https://newdomain.com$request_uri;

I tried so, but it does not work

    server {
    listen 443 ssl;
    server_name  example.com www.example.com;

    location = / {
    return 301 https://newdomain.com/?from=example.com;
    }

    return 301 https://newdomain.com$request_uri;
}

Thanks for help


Solution

  • Your last "return 301" was overruling those inside the location.

    server {
      listen 443 ssl;
      server_name  example.com www.example.com;
    
      location = / {
        return 301 https://newdomain.com/?from=example.com;
      }
    
      location / {
        return 301 https://newdomain.com$request_uri;
      }
    }