'How to deploy backend and frontend on the same server but different path with Nginx

I need to deploy the frontend in https://service.domain.it and the backend in https://service.domain.it/api. I've done a deploy configuration but I'm having troube with spring security + JWT Authentication. This is the configure method of WebSecurityConfigurerAdapter

@Override
public void configure(HttpSecurity http) throws Exception {
    http.csrf().disable()
            .authorizeRequests()
            .antMatchers("/public/**").permitAll() //login/logout/recoverypassw
            .antMatchers("/user/**").hasAnyRole("USER","ADMIN")
            .antMatchers("/admin/**").hasRole("ADMIN")
            .anyRequest().authenticated()
            .and().exceptionHandling().authenticationEntryPoint(jwtAuthenticationEntryPoint).
            and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).
            and().addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
}

And this is the nginx configuration

#service.domain.it
server{
        listen 443 ssl;
        server_name service.domain.it;
        ssl_certificate /etc/letsencrypt/live/service.domain.it/fullchain.pem;
        ssl_certificate_key /etc/letsencrypt/live/service.domain.it/privkey.pem;
        location /api/ {
                #backend
                proxy_pass http://localhost:8085;
        }

       location / {
               #frontend
               index index.html;
                alias /var/www/html/Service/;
       }
}
server{
        listen 80;
        server_name service.domain.it;
        return 301 https://service.domain.it$request_uri;
}

What should I do?



Solution 1:[1]

Your backend service does not understand the /api used in your proxy_configuration. You must rewrite the URI before sending it to the backend.

location /api {

   rewrite ^/api/(.*) /$1 break;
   proxy_pass http://backend/;

}

This will remove the /api from the URI before sending it to the backend.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Timo Stark