Nginx proxy_pass到带有尾部斜杠的变量失败 [英] Nginx proxy_pass to variable with trailing slash fails

查看:199
本文介绍了Nginx proxy_pass到带有尾部斜杠的变量失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了需要将proxy_pass设置为变量的问题,但是当我将其设置为变量时,它在后端服务器上无法正确解析

I'm having an issue where I need to make the proxy_pass a variable, but when I make it a variable, it fails to resolve correctly on the backend server

nginx -v
nginx version: nginx/1.6.2

这是工作的:

  server {
    listen 443 ssl;
    ssl on;
    server_name api.hostname.com;

    include ssl_params;

    location = /v1 {
      return 302 /v1/;
    }

    location /v1/ {
      proxy_pass        http://internal-api.hostname.com.us-east-1.elb.amazonaws.com/;
      proxy_set_header  Host            $host;
      proxy_set_header        X-Real-IP       $remote_addr;
      proxy_set_header  X-Forwarded-For $proxy_add_x_forwarded_for;
    }

  }

这是坏的

  server {
    listen 443 ssl;
    ssl on;
    server_name api.hostname.com;

    include ssl_params;

    location = /v1 {
      return 302 /v1/;
    }

    location /v1/ {
      resolver 10.0.0.2;
      set $backend "http://internal-api.hostname.com.us-east-1.elb.amazonaws.com/";
      proxy_pass        $backend;
      proxy_set_header  Host            $host;
      proxy_set_header        X-Real-IP       $remote_addr;
      proxy_set_header  X-Forwarded-For $proxy_add_x_forwarded_for;
    }

  }

https://api.hostname.com/v1/profile 的后端结果工作的是:

The backend results for https://api.hostname.com/v1/profile on the working one is:

<-- GET /profile
--> GET /profile 200 16ms 349b

但是坏了的

<-- GET /
--> GET / 401 1ms 12b

我尝试过:

set $backend "internal-api.hostname.com.us-east-1.elb.amazonaws.com";
proxy_pass http://$backend/

set $backend "internal-api.hostname.com.us-east-1.elb.amazonaws.com/";
proxy_pass http://$backend/

每当我在proxy_pass中使用变量时,它会将所有内容转发到后端的/(根),这绝对不是我想要的.

Any time I'm using variables in the proxy_pass, it forwards everything to / (root) on the backend, definitely not what I was intending.

推荐答案

我遇到了完全相同的问题(需要变量,因为在AWS上内部IP更改了).经过两天的测试/调查,我认为已找到一种有效的配置(变量中没有/或proxy_pass中,但有一个"rewrite break"以删除后端请求上不需要的路径):

I have exactly the same problem (need variable because on AWS the internal IP change). After two days of test/investigation, I think have found a working configuration (with no / in variable or proxy_pass but with a "rewrite break" for remove the unwanted path on backend request):

resolver 10.0.0.2;
set $backend "http://internal-api.hostname.com.us-east-1.elb.amazonaws.com";
location /v1/ {
      proxy_pass        $backend;
      proxy_set_header  Host            $host;
      proxy_set_header        X-Real-IP       $remote_addr;
      proxy_set_header  X-Forwarded-For $proxy_add_x_forwarded_for;
      rewrite ^/v1/(.*) /$1 break;
}

这篇关于Nginx proxy_pass到带有尾部斜杠的变量失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆