简体   繁体   中英

Nginx location rewrite rules not working behind ELB

I have 2 ec2 instances behind an App Load Balancer which reroute the traffic to the desired instance according to the path:

  • www.example.com/hello => instance 1
  • www.example.com/goodbye => instance 2

Nginx servers configuration

# Hello server config
server {
    listen       80;
    server_name  localhost;

    location / {
        root  /home/ubuntu/welcome;
    }

    location = /hello {
        root  /home/ubuntu/api;
    }
# Goodbye server config
server {
    listen       80;
    server_name  localhost;

    location / {
        root  /home/ubuntu/welcome;
    }

    location = /goodbye {
        root  /home/ubuntu/api;
    }

I have created a simple index.html file in each server under the root folder as specified in the config files, so that the instance1 return "Hello" and instance2 return "Goodbye". However www.example.com/hello and www.example.com/goodbye always return 404 not found. I did reload my Nginx service and even restarted.

PS: For the sake of testing, I created another instance with Nginx not hidden behind an ELB and edited the config to look similar and it seems to work so I am not sure what did I do wrong with the ones behind the ELB.

Managed to solve this by moving the root outside of the location brackets and update the name of my folders to match the name of location and it works. so now it looks like this.

server {
        listen       80;
        server_name  localhost;
        root  /home/ubuntu/api;

        location / {        
        }

        location = /hello {
        }
}

Path to hello source code is /home/ubuntu/api/hello/

Path to goodbye source code => /home/ubuntu/api/goodbye/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM