Search code examples
nginxurl-rewritingsubdomain

NGINX - Redirecting certain routes to a subdomain


I created a project, where I have:

  1. my-project.com to show my Angular 8 App
  2. api.my-project.com to access my Symfony 5 API

I built a very basic landing page on my Angular app, but now, I changed my mind and I want to have my angular app into app.my-project.com and keep the my-project.com to show a beautifull landing page.

The problem is that there are some clients that are already using the service on the main domain, and that request should be redirected to the app.my-project.com subdomain.

Should be something like this:

my-project.com/login -> app.my-project.com/login

my-project.com/pm-something -> app.my-project.com/pm-something

Here is a pseudocode of what I need:

if( url.includes('login') or url.includes('pm-') ) {
    redirectTo(app.my-project.com)
}

I thought the easiest way to achieve that is to rewriting the routes in my NGINX config file, but I am not sure the correct way to do it.

Thanks in advance.


Solution

  • NGINX chooses request URI processing rules according to defined location blocks within the server configuration. Official documentation on this directive is here, and here are some additional explanations. You can achieve desired behavior using two prefix locations:

    location /login {
        return 301 $scheme://app.my-project.com$request_uri;
    }
    location /pm- {
        return 301 $scheme://app.my-project.com$request_uri;
    }
    

    This two prefix locations could be replaced by a single regex matching location:

    location ~ ^/(login|pm-) {
        return 301 $scheme://app.my-project.com$request_uri;
    }
    

    NGINX uses system PCRE library and the general PCRE regex syntax, except you should not use delimiter characters for regex patterns (matching against a regex specified using ~ (case-sensitive matching), ~* (case-insensitive matching) or !~/!~* (case-sensitive/case-insensitive non-matching) operators). Additionally you are not required to prefix / character with a backslash (although you still can do it, it won't change the regex pattern meaning).