Nginx 代理配置,通过 http 代理访问后端 API

Nginx 代理配置,通过 http 代理访问后端 API

我需要 Nginx Web 服务器连接到监听端口 443 的 https 服务器。服务器机器https无法直接访问该服务器Nginx,要访问该https服务器,nginx服务器需要设置http_proxyhttps:proxy参数。

我们之前使用过 Apache,并且已经实现了相同的使用参数,该参数允许 Apache 服务器通过代理服务器ProxyRemote * http://10.23.45.32:3128连接到远程服务器。https

我们正在从 apache 迁移到 Nginx,需要知道如何添加代理规则,以便Nginx服务器可以将请求传递给https服务器。

我为 Nginx 设置了以下配置。

server {
  listen       80;
  server_name  localhost;
  access_log  /var/log/nginx/localhost.access.log;
  location / {
         proxy_pass http://localhost:9000;
         proxy_http_version 1.1;
         proxy_set_header Upgrade $http_upgrade;
         proxy_set_header Connection 'upgrade';
         proxy_set_header Host $host;
         proxy_cache_bypass $http_upgrade;
  }

  #below path is working fine
  location /cities.json {
    proxy_pass      http://hostname.net:8080/cities.json;
  }
  #below rule is working fine
  location /states/ {
    proxy_pass     http://hostname.net:8080;
  }
  #below rule is giving 504 gateway timeout error.
  location /auth {
    #cannot call https://authenticationserver.net directly and need to go through proxy by setting http_proxy to http://proxy.host.net:3128
    proxy_pass    https://authenticationserver.net:443;
  }
}

在 Apache 中,我曾经进行以下配置来设置代理:

<VirtualHost *:8000>
  ServerName hostname.net
  <Location /balancer-manager>
    SetHandler balancer-manager
    Order Deny,Allow
    Deny from all
    Allow from all
  </Location>
  <Proxy balancer://authncluster>
    BalancerMember https://target.host.net
  </Proxy>
  <Proxy *>
    Order Allow,Deny
    Allow From All
  </Proxy>
  ProxyRemote * http://proxy.host.net:3128
  SSLProxyEngine On
  ProxyPreserveHost On
  ProxyPass /balancer-manager !
  ProxyPass /authn/ balancer://authncluster/authn/
  ProxyTimeout 300
</VirtualHost>

希望这有帮助。请告诉我如何在 Nginx 中进行配置。

答案1

类似这样的操作就可以了(路径会出错,因为你的问题似乎没有指定足够的细节。关键是 nginx 选择了最具体的匹配 - 你可以对此做好准备这里

location / {
   proxy_pass http://localhost:9000;
   proxy_http_version 1.1;
   proxy_set_header Upgrade $http_upgrade;
   proxy_set_header Connection 'upgrade';
   proxy_set_header Host $host;
   proxy_cache_bypass $http_upgrade;
}

location /otherurl {
  proxy_pass http://localhost:9001;
  # etc
}

location /thirdurl {
  proxy_pass http://localhost:9002;
  # etc
}

相关内容