nginx部署后无法访问swagger文档

27 阅读1分钟

问题描述

在进行服务测试部署时, 需要将多个应用用一个端口访问,
目前使用的是nginx, 部署后发现无法访问后端swagger文档

案例如下

比如3个后端服务分别配置如下端口,
aaa.jar 端口: 9091
bbb.jar 端口: 9092
ccc.jar 端口: 9093

现在从测试服务器的 9999 端口去访问这3个服务
https://ip:port/api_aaa/ => http://127.0.0.1:9091/api_aaa/
https://ip:port/api_bbb/ => http://127.0.0.1:9092/api_bbb/
https://ip:port/api_ccc/ => http://127.0.0.1:9093/api_ccc/

nginx.conf文件内容如下:

server {
  listen 9999;
  server_name localhost;

  location /api_aaa/ {
    proxy_pass http://127.0.0.1:9091;
  }

  location /api_bbb/ {
    proxy_pass http://127.0.0.1:9092;
  }

  location /api_ccc/ {
    proxy_pass http://127.0.0.1:9093;
  }
...
}

原因分析

api_aaa 为例, 虽然在拦截程序里面加了 swagger资源 的白名单, 如下:

"/swagger-resources/**",
"/swagger-ui.html",
"/doc.html",
"/images/**",
"/webjars/**",
"/v2/api-docs"

但是通过 nginx 转发的时候的请求带着 /api_aaa 前缀, 访问的是 http://127.0.0.1:9091/api_aaa/doc.html 而不是 http://127.0.0.1:9091/doc.html

解决方案

在不调整jar包, 且不变更前后端调用url结构的情况下,
只能额外配置 swagger 相关资源的跳转, 例如:

  location /api_aaa/doc.html {
    proxy_pass http://127.0.0.1:9091/doc.html;
    index index.html index.htm;
  }

  location /api_aaa/webjars {
    proxy_pass http://127.0.0.1:9091/webjars;
    index index.html index.htm;
  }

  location /api_aaa/swagger-resources {
    proxy_pass http://127.0.0.1:9091/swagger-resources;
    index index.html index.htm;
  }

  location /api_aaa/v2 {
    proxy_pass http://127.0.0.1:9091/v2;
    index index.html index.htm;
  }