Search code examples
ubuntunginxnetworkingnginx-configubuntu-20.04

How to set up URL forwarding in nginx ubuntu?


Current env is ubuntu server 20, nginx installed.

Now what I want to achieve is http://192.168.1.5/c1234 --> http://192.168.1.5:8081/web

http://192.168.1.5/c5678 --> http://192.168.1.5:8082/web

port info is stored in a csv file , like

c1234=8081
c5678=8082

is it possible to use grep to get that port ?

What keyword I should search? Proxy or forwarding or rewrite? Any web link is welcomed.

Thank You


Solution

  • Nginx Reverse Proxy would help with this.

    This setup allows you to redirect incoming requests from Nginx to backend servers based on the path.

    location ~ ^/c1234(.*)$ {
        proxy_pass http://127.0.0.1:8081/web$1;
    }
    
    location ~ ^/c5678(.*)$ {
        proxy_pass http://127.0.0.1:8082/web$1;
    }
    
    • The ~ ^/c1234(.*)$ is a regular expression matching the path that starts with /c1234

    • proxy_pass is the directive to redirect the traffic.

    • Just change the 127.0.0.1 IP address to the needed IP address.

    Test the configuration and reload NGINX

    sudo nginx -t
    sudo systemctl reload nginx
    

    You should be able to achieve

    http://192.168.1.5/c1234 --> http://192.168.1.5:8081/web
    
    http://192.168.1.5/c5678 --> http://192.168.1.5:8082/web
    

    To learn more about it, see the next documentation:

    https://docs.nginx.com/nginx/admin-guide/web-server/reverse-proxy/