javaspring-bootswaggerspringdoc-openapi-ui

Hosting swagger-ui behind nginx proxy


we have a setup where we have deployed springdoc-openapi-starter-webmvc-ui with Spring Boot 3.1.5. The spring boot server is running on port 8080. We have setup nginx so that all requests that start with /api are forwarded to spring boot:

location ~ ^/api(/|$) {
        rewrite ^/api(/|$)(.*)$ /$2 break;
        proxy_pass http://127.0.0.1:8080;  # Forward requests to backend server
        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;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; # per https://springdoc.org/index.html#how-can-i-deploy-springdoc-openapi-starter-webmvc-ui-behind-a-reverse-proxy
    proxy_set_header X-Forwarded-proto https; # per https://springdoc.org/index.html#how-can-i-deploy-springdoc-openapi-starter-webmvc-ui-behind-a-reverse-proxy
    proxy_set_header X-Forwarded-Prefix "/api"; # per https://springdoc.org/index.html#how-can-i-deploy-springdoc-openapi-starter-webmvc-ui-behind-a-reverse-proxy
    }

The last 3 lines are per what we could gather from this link. In our application.properties we have set:

server.forward-headers-strategy=NATIVE
server.use-forward-headers=true

Our expectation is that with this setup we should see the swagger UI at /api/swagger-ui/index.html. However when we navigate to that URL we see following:

and the developer tools in the browser show its trying to make request to /v3/api-docs to fetch the config whereas it should be making request to /api/v3/api-docs - we tested this URL works. All requests that Swagger UI is making to the backend need to be prefixed with /api. This is our core problem.

How can we fix this?


Solution

  • Managed to fix it and making note for self. The fix is to remove

    rewrite ^/api(/|$)(.*)$ /$2 break;
    

    from NGINX conf (i.e., don't rewrite the URL) and add following two properties to Spring boot application.properties:

    server.servlet.contextPath=/api
    server.forward-headers-strategy=framework