Spring Boot Swagger经Nginx反向代理无法加载配置的解决咨询
解决Swagger在Nginx反向代理下的配置加载问题
问题原因
Swagger UI默认会从根路径(如/v3/api-docs/swagger-config)请求配置文件,但你的服务通过Nginx代理到了带前缀的路径下(/template-order-service/、/template-product-service/),导致请求路径不匹配,返回404。
解决方案(分主流Swagger实现)
1. 使用SpringDoc OpenAPI(Spring Boot 2.4+推荐)
针对每个服务,修改配置文件或添加配置类,指定Swagger的路径前缀:
方法一:通过配置文件(application.yml)
template-order-service配置:
springdoc: swagger-ui: # 自定义Swagger UI访问路径 path: /template-order-service/swagger-ui.html # 指定配置文件的请求路径 config-url: /template-order-service/v3/api-docs/swagger-config api-docs: # 指定API文档的请求路径 path: /template-order-service/v3/api-docs
template-product-service配置:
springdoc: swagger-ui: path: /template-product-service/swagger-ui.html config-url: /template-product-service/v3/api-docs/swagger-config api-docs: path: /template-product-service/v3/api-docs
方法二:通过Java配置类
创建配置类,显式设置Swagger的服务路径和UI参数:
@Configuration public class OpenApiConfig { // 设置OpenAPI的基础服务路径 @Bean public OpenAPI customOpenAPI() { return new OpenAPI() .servers(List.of(new Server().url("/template-order-service"))); } // 配置Swagger UI的路径参数 @Bean public SwaggerUiConfigParameters swaggerUiConfigParameters() { SwaggerUiConfigParameters parameters = new SwaggerUiConfigParameters(); parameters.setConfigUrl("/template-order-service/v3/api-docs/swagger-config"); parameters.setUrl("/template-order-service/v3/api-docs"); parameters.setPath("/template-order-service/swagger-ui.html"); return parameters; } }
(注意:template-product-service需要将上述代码中的template-order-service替换为对应前缀)
2. 使用Springfox Swagger2(旧版实现)
如果你的项目使用的是Springfox,可通过以下方式配置:
方法一:配置文件(application.properties)
template-order-service配置:
# 设置Swagger UI的基础路径 springfox.documentation.swagger-ui.base-url=/template-order-service # 指定配置文件的请求路径 springfox.documentation.swagger-ui.config-url=/template-order-service/v2/api-docs/swagger-config
方法二:Java配置类
@Configuration @EnableSwagger2 public class SwaggerConfig { @Bean public Docket api() { return new Docket(DocumentationType.SWAGGER_2) .select() .apis(RequestHandlerSelectors.basePackage("你的接口包路径")) .paths(PathSelectors.any()) .build() .pathMapping("/template-order-service"); // 设置路径前缀 } @Bean public UiConfiguration uiConfig() { return UiConfigurationBuilder.builder() .configUrl("/template-order-service/v2/api-docs/swagger-config") .build(); } }
验证配置
修改完成后重启服务,访问以下路径即可正常加载Swagger:
- 订单服务:
http://localhost:8080/template-order-service/swagger-ui.html - 商品服务:
http://localhost:8080/template-product-service/swagger-ui.html
内容的提问来源于stack exchange,提问作者clsbartek
相关产品推荐
相关产品推荐

