简体   繁体   English

Nginx 位置重写规则在 ELB 后面不起作用

[英]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:我在 App Load Balancer 后面有 2 个 ec2 实例,它们根据路径将流量重新路由到所需的实例:

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

Nginx servers configuration Nginx 服务器配置

# 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".我在配置文件中指定的根文件夹下的每个服务器中创建了一个简单的 index.html 文件,以便 instance1 返回“Hello”,instance2 返回“Goodbye”。 However www.example.com/hello and www.example.com/goodbye always return 404 not found.但是 www.example.com/hello 和 www.example.com/goodbye 总是返回 404 not found。 I did reload my Nginx service and even restarted.我确实重新加载了我的 Nginx 服务,甚至重新启动了。

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. PS:为了测试,我创建了另一个实例,Nginx 没有隐藏在 ELB 后面,并将配置编辑为看起来相似,它似乎可以工作,所以我不确定我对 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/你好源代码的路径是/home/ubuntu/api/hello/

Path to goodbye source code => /home/ubuntu/api/goodbye/再见源代码的路径 => /home/ubuntu/api/goodbye/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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