【问题标题】:nginx multisite reverproxy using path variable使用路径变量的 nginx 多站点 reverproxy
【发布时间】:2022-01-20 19:22:15
【问题描述】:

我在单个实例上有多站点设置,我的意思是使用站点 ID,我正在切换内容、徽标主题颜色等,并且每个站点都有不同的域名。

路径

http://localhost:3000/{{site_id}}/ 
http://localhost:3000/{{site_id}}/about-us/
http://localhost:3000/{{site_id}}/product/1232/slug

etc...

举例

http://localhost:3000/1 => site-a.local
http://localhost:3000/2 => site-b.local
http://localhost:3000/3 => site-c.local

我用的是nginx,从80端口反向代理到3000。如何在nginx中转发站点id

server {

   listen 80;
   listen [::]:80;
   
   server_name site-a.local;


   location ~ /(.*) {
    
        proxy_pass http://localhost:3000/1;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    
    }

}


server {

   listen 80;
   listen [::]:80;
   
   server_name site-b.local;


   location ~ /(.*) {
    
        proxy_pass http://localhost:3000/2;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
     
    }

}

由于某种原因,上述想法不起作用,有人可以帮助我吗?

【问题讨论】:

  • 什么不起作用?我是对的,您正在尝试将多个具有不同域的 nginx 服务器块代理到相同的上游 127.1:3000 但具有不同的位置?
  • 是的正确,我有一个应用程序在 3000 端口运行,它显示基于第一个路径变量 /{site_id} 的不同内容,所以我希望 nginx 将不同的域路由到不同的 site_id,我不向用户显示 site_id 的内容,我想像这样屏蔽http://localhost:3000/1/ => site-a.local

标签: nginx nginx-reverse-proxy


【解决方案1】:
upstream node {
  server 127.0.0.1:3000;
  keepalive 32;
}



server {
  server_name site-a.local;
  listen 80;
  location / {
    proxy_pass http://node/1/;
    proxy_set_header Host $host;
  }
}


server {
  server_name site-b.local;
  listen 80;
  location / {
    proxy_pass http://node/2/;
    proxy_set_header Host $host;

  }
}


server {
  listen 3000;
  location /1/ { return 200 "Hello from 1 with URL $uri"; }
  location /2/ { return 200 "Hello from 2 with URL $uri"; }
}

通过这个你代理到你的节点后端,监听端口3000

$:/etc/nginx/conf.d# curl -H "Host: site-a.local" 127.1/test/location/
Hello from a with URL /a/test/location/


$:/etc/nginx/conf.d# curl -H "Host: site-b.local" 127.1/test/location/
Hello from b with URL /b/test/location/

【讨论】:

  • 抱歉,我出站了,我收到类似这样的错误“proxy_pass”不能在正则表达式给出的位置、命名位置或“if”语句中包含 URI 部分,或者在“limit_except”块内
  • 抱歉我的回复晚了。在我的配置中没有正则表达式位置。您需要基于 REGEX 的位置吗?请再次检查您的配置,并确保位置配置中没有~
猜你喜欢
  • 1970-01-01
  • 2023-04-02
  • 1970-01-01
  • 1970-01-01
  • 2015-03-15
  • 2021-08-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多