nginx根据主机名中的索引反向代理到不同的应用程序



以前,我有一个可以在DNSstaging.example.com/后面访问的临时环境。这个地址后面是一个nginx代理,配置如下。请注意,我的代理要么重定向

  • To a(s3 behind(cloudfront distribution(app1(
  • 通过转发主机名(让我们考虑一下我的ALB能够根据主机名选择合适的应用程序((app2(
server {
listen 80;
listen 443 ssl;
server_name
staging.example.com
;
location / {
try_files /maintenance.html @app1;
}
location ~ /(faq|about_us|terms|press|...) {
try_files /maintenance.html @app2;
}
[...] # Lots of similar config than redirects either to app1 or app2
# Application hosted on s3 + CloudFront
location @app1 {
proxy_set_header Host app1-staging.example.com;
proxy_pass http://d2c72vkj8qy1kv.cloudfront.net;
}
# Application hosted behind a load balancer
location @app2 {
proxy_set_header Host app2-staging.example.internal;
proxy_set_header X-ALB-Host $http_host;
proxy_pass https://staging.example.internal;
}
}

现在,我的团队需要更多的登台环境。我们还没有准备好过渡到docker部署(最终目标是能够为我们需要测试的每个分支生成一个完整的基础设施……考虑到我们的团队规模,这有点过头了(,我正在尝试一些技巧,这样我们就可以使用大致相同的nginx配置来轻松地获得更多的登台环境。

假设我已经创建了几个具有index_i的DNS名称,如staging1.example.comstaging2.example.com。因此,我的nginx代理将接收具有类似staging#{index_i}.example.com的主机标头的请求

我想做的事:

  • 对于我的s3+Cloudfront应用程序,我正在考虑将我的文件嵌套在[bucket_id]/#{index_i}/[app1_files]下(以前它们直接位于根文件夹[bucket_id]/[app1_files]中(
  • 对于我的负载均衡器应用程序,假设我的负载平衡器知道在哪里调度https://staging#{iindex_i}.example.com请求

我正试图拉出类似的东西

# incoming host : staging{index_i}.example.com`
server {
listen 80;
listen 443 ssl;
server_name
staging.example.com
staging1.example.com 
staging2.example.com # I can list them manually, but is it possible to have something like `staging*.example.com` ?
;
[...]
location @app1 {
proxy_set_header Host app1-staging$index_i.example.com; # Note the extra index_i here
proxy_pass http://d2c72vkj8qy1kv.cloudfront.net/$index_i; # Here proxy_passing to a subfolder named index_i
}
location @app2 {
proxy_set_header Host app2-staging$index_i.example.internal; # Note the extra index_i here
proxy_set_header X-ALB-Host $http_host;
proxy_pass http://staging$index_i.example.internal; # Here I am just forwarding the host header basically
}

所以最终我的问题是-当我的nginx服务器接收到连接时,我可以从请求主机头中提取index_i变量吗(可能使用一些regex?(-如果是,如何使用index_i有效地实现app1和app2块?

在考虑了其他几个问题后,我能够想出这个完美的配置:可以使用主机名中的正则表达式提取所述变量。

不利的一面是,对于我的静态单页应用程序,为了使其与S3协同工作,我必须为每个"暂存索引"创建一个bucket(因为S3上的静态托管与404上使用的网站托管/单个index.html协同工作(。这反过来又使得在我的(以前的(s3之前不可能使用单个Cloudfront发行版。

下面是一个使用代理的例子,该代理具有创建反应应用程序前端和ALB 后面的服务器端渲染

server {
listen 80;
listen 443 ssl;
server_name ~^staging(?<staging_index>d*).myjobglasses.com$
location @create-react-app-frontend {
proxy_pass http://staging$staging_index.example.com.s3-website.eu-central-1.amazonaws.com;
}
location @server-side-rendering-app {
# Now Amazon Application Load Balancer can redirect traffic based on ANY HTTP header
proxy_set_header EXAMPLE-APP old-frontend;
proxy_pass https://staging$staging_index.myjobglasses.com;
}

最新更新