Search code examples
nginxwebserver

How to perform multiple redirects in NGINX


I am making my first nginx configuration file. I have 2 goals:

  1. redirect all non "www" requests to "www" version
  2. redirect all traffic which used to be served in a subdirectory of an ip addressed folder

ie:

mysite.com >>> "www.mysite.com"

and

123.456.789.123/BETA >>> "www.mysite.com"

Here is my config:

    server {
            listen 80;
            listen 443 ssl;
            server_name 123.456.789.123;
            return 301 $scheme://www.mysite.com$request_uri;
    }
    server {
            listen 80;
            listen 443 ssl;
            server_name mysite.com;
            rewrite ^(.*)$ $scheme://www.mysite.com$1;
            location ~* ^/BETA/ {
                    return 301 /;
            }
    }

mysite.com >>> "www.mysite.com" works but 123.456.789.123/BETA >>> "www.mysite.com" is instead giving: "www.mysite.com/BETA"

It feels like I am doing something wrong here... Should there be 2 "server" blocks? If so how should I structure this to use one? Is "location" the right way to rewrite the subdirectory to the root? Is it maybe causing some conflict with the re-write in the same server block? Should I create a 3rd server block to rewrite the subdirectory to the root? Is there a way to directly rewrite 123.456.789.123/BETA to www.mysite.com ?

Thanks for help in advance!


Solution

  • From the documentation: https://www.nginx.com/blog/creating-nginx-rewrite-rules/

    This should do it, I modified your code to redirect 123.456.789.123/BETA to www.mysite.com (just remove the $request_uri for requests to 123.456.789.123/BETA). For any other pages requested of 123.456.789.123, such as 123.456.789.123/foo will redirect to www.mysite.com/foo.

    server {
            listen 80;
            listen 443 ssl;
            server_name 123.456.789.123;
            location = /BETA {
                    return 301 $scheme://www.mysite.com;
            }
            return 301 $scheme://www.mysite.com$request_uri;
    }
    server {
            listen 80;
            listen 443 ssl;
            server_name mysite.com;
            rewrite ^(.*)$ $scheme://www.mysite.com$1;
    }
    

    If you want to redirect subpages of /BETA, such as /BETA/foo, to www.mysite.com as well, remove the '=' in that line before /BETA.

    EDIT: Not sure if this was clear, but you'll need a third server block with server_name www.mysite.com that actually serves your website.