Backend Development 7 min read

How to Apply a Global URL Prefix to All Spring Boot Controllers

This article explains multiple ways to apply a common URL prefix to all Spring Boot controllers, covering servlet‑context configuration, property settings, annotation‑based approaches, server‑side forwarding, and Nginx reverse‑proxy techniques, with code samples and discussion of their advantages and drawbacks.

Spring Full-Stack Practical Cases
Spring Full-Stack Practical Cases
Spring Full-Stack Practical Cases
How to Apply a Global URL Prefix to All Spring Boot Controllers

1. Introduction

In Spring Boot each controller can have its own URL mapping, but sometimes a unified prefix is desired. This article explores several methods to set a common prefix for all controllers.

2. Based on Servlet Context

2.1 Configure DispatcherServlet Bean

<code>@Configuration
public class DispatcherServletCustomConfiguration {
    @Bean
    public DispatcherServlet dispatcherServlet() {
        return new DispatcherServlet();
    }

    @Bean
    public ServletRegistrationBean dispatcherServletRegistration() {
        ServletRegistrationBean registration = new ServletRegistrationBean(
            dispatcherServlet(), "/api/");
        registration.setName("dispatcherServlet");
        return registration;
    }
}
</code>

This registers a DispatcherServlet with the URL prefix /api/ , so all endpoints must be accessed through that base path.

2.2 Using Configuration Properties

Spring Boot 2.x and later allow setting the context path in application.yml :

<code>server:
  servlet:
    contextPath: /api
</code>

For earlier versions the same effect can be achieved with:

<code>server:
  contextPath: /api
</code>

Or with Spring MVC properties:

<code>spring:
  mvc:
    servlet:
      path: /api
</code>

These approaches affect every endpoint in the application.

3. Annotation‑Based Methods

3.1 Using SpEL with @RequestMapping

<code>@Controller
@RequestMapping(path = "${pack.app.apiPrefix}/users")
public class UserController {
}
</code>

The prefix is defined in the configuration property pack.app.apiPrefix .

3.2 Custom Annotation

<code>@RequestMapping(value = "/api/")
public @interface PackMapping {
}

// Usage
@RestController
@PackMapping
public class SomeController {
    @RequestMapping("/users")
    public String getAll() {
        return "...";
    }
}
</code>

Custom annotations allow fine‑grained control, applying the prefix only to selected controllers.

4. Server‑Side Forwarding

<code>@RestController
public class EndpointController {
    @GetMapping("/endpoint1")
    public String endpoint1() { return "Hello from endpoint 1"; }

    @GetMapping("/endpoint2")
    public String endpoint2() { return "Hello from endpoint 2"; }
}
</code>

A routing controller forwards requests based on a custom header:

<code>@Controller
@RequestMapping("/api/endpoint")
public class ApiPrefixController {
    @GetMapping
    public ModelAndView route(ModelMap model, HttpServletRequest request) {
        String action = request.getHeader("X-ACTION");
        return switch (action) {
            case null -> new ModelAndView("forward:/error");
            case "xxx" -> new ModelAndView("forward:/endpoint1", model);
            case "zzz" -> new ModelAndView("forward:/endpoint2", model);
            default -> new ModelAndView("forward:/home");
        };
    }
}
</code>

5. Nginx Reverse Proxy

<code>server {
    listen 80;
    server_name default;

    location /api/ {
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-NginX-Proxy true;

        rewrite ^/api/(.*)$ /$1 break;
        proxy_pass http://www.pack.com;
    }
}
</code>

This method adds the prefix at the web server level without modifying application code.

Pros and Cons

Servlet‑context and property approaches affect every endpoint, which may be unsuitable for services that need unprefixed paths (e.g., OAuth callbacks). Annotation‑based solutions provide granular control, allowing only selected controllers to use the prefix.

backendSpring Bootnginxannotationdispatcher-servleturl-prefix
Spring Full-Stack Practical Cases
Written by

Spring Full-Stack Practical Cases

Full-stack Java development with Vue 2/3 front-end suite; hands-on examples and source code analysis for Spring, Spring Boot 2/3, and Spring Cloud.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.