swagger-ui 通过nginx转发时的巨坑!!!
先上pom
<dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.8.0</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.8.0</version> </dependency>
配置文件
这样子配上就可以用了。
开始上线测试的时候,系统搭建在线上,用的docker。本身没啥问题, /swagger-ui.html 就可以访问了的。
结果呢。测试服务器装了nginx,我项目用docker-compose 写好了nginx的,服务器又只开放80 443。
所有就用在服务器的nginx上做了个转发,我docker里面的nginx端口改成了81。
服务器的nginx简单做了代理如下
server { listen 80; server_name test.xxx.com ; location / { proxy_pass http://127.0.0.1:81; proxy_set_header Host $http_host; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; } }
重启nginx,输入地址 xxx/swagger-ui.html
懵逼了,弹出如下提示
Unable to infer base url. This is common when using dynamic servlet registration or when the API is behind an API Gateway. The base url is the root of where all the swagger resources are served. For e.g. if the api is available at http://example.org/api/v2/api-docs then the base url is http://example.org/api/. Please enter the location manually:
于是乎,百度总结出如下三个方案。还有说换版本的。
(1).把@EnableSwagger2注解加在主启动类
(2).主启动类加上@ComponentScan("swagger配置类所在包")
(3).将WebSecurityConfig与ScheduleConfig置于同一路径
挨个试了 都不行。最后一想到外层有个nginx,内层还有个nginx。会不会是转发除了问题。于是仔细分析,发现是缓存导致的。
更改后的nginx配置如下
外包nginx
server { listen 80; server_name test.xxx.com ; location / { proxy_buffer_size 64k; proxy_buffers 32 32k; proxy_busy_buffers_size 128k; proxy_pass http://127.0.0.1:81; proxy_set_header Host $http_host; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; } }
docker内的nginx
location ~* ^(/v2|/webjars|/swagger-resources|/swagger-ui.html){ proxy_buffer_size 128k; proxy_buffers 32 128k; proxy_busy_buffers_size 128k; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $remote_addr; #proxy_set_header Host $host:$server_port; proxy_set_header X-Forwarded-Proto $scheme; proxy_set_header X-Forwarded-Port $server_port; proxy_pass http://backends; }
重启,然后可以访问了。