Home > database >  forward the home path to another server via nginx
forward the home path to another server via nginx

Time:11-26

i have a flask server that runs on port 5000 and I have a domain. I am deploying flask with gunicorn and nginx. What I want to do is to be able to route "www.mydomain.com" to a different server say "www.mydomain.webflow.io", but keep all the requests coming to other paths say "www.mydomain.com/path1" or "www.mydomain.com/path2" to the same nginx host, but redirect to 5000 port number.

How can i configure nginx for this. Do I need to make separate entry for each path (under location)?

CodePudding user response:

You can do something like this:

server {
    listen 80;
    server_name example.com;

    location = / {
        # this location block handles only request which ends with /

        # redrects to another domain
        return 301 https://example.otherdomain.tld;

        # proxies to another backend
        # proxy_pass http://localhost:6000/;
    }
    
    location / {
        # this location block handles everything else
        proxy_pass http://localhost:7777/;
    }
}

The above nginx config has two location blocks.

The first location block handles every request which ends only with a /. For example:

https://example.com/

# a / is appended automatically so this works as well
https://example.com

The second location block handles everything which does not match only /.

For example:

https://example.com/api
https://example.com/static/img.png

I have included an option that redirects you to a new domain with HTTP status code 301 (Permanent)

return 301 https://example.otherdomain.tld;

# https://example.com -> https://example.otherdomain.tld;

The second option passes the request to another backend.

proxy_pass http://localhost:6000/;

You should only use one of both options

  • Related