域名配置多一层路径,swagger里的接口无法正常访问,手动加上多出来的路径可以访问

nginx配置了域名为aa.bb.com/api这样,swagger可以正常打开 但是访问里面接口的时候路径上就没有了/api导致访问失败,这样怎么解决呢


当配置了nginx的location路径时,swagger里面的接口路径也需要对应修改,否则会出现找不到接口的情况。
可以在swagger ui的配置中添加basePath属性,值为nginx配置的location路径,这样访问接口时就会自动加上这个basePath。
例如:
swagger:
  basePath: /api
或者在代码中配置 swagger 对象添加basePath属性:
java
@Configuration
public class SwaggerConfig {

  @Bean
  public Docket createRestApi() {
    return new Docket(DocumentationType.SWAGGER_2)
        .apiInfo(apiInfo())
        .select()
        .apis(RequestHandlerSelectors.basePackage("com.example.controller"))
        .paths(PathSelectors.any()) 
        .build()
        .pathMapping("/") 
        .enableUrlTemplating(true)
        .basePath("/api"); // 设置basePath
  }
}
这样swagger生成的接口路径就会自动加上/api前缀,就可以正确访问了。
另外在nginx也可以通过location里面正则匹配来自动加上/api前缀,实现重写。
这两种方式可以解决这个问题,选择合适的方式即可。