Setting a base url for urls generated by Spring
Asked Answered
I

1

7

We've got a restful api running using spring which generates HATEOAS links. When I run the service locally, they are generated fine, but on our server, which hosts tomcat behind apache which proxies the app to /api/ (locally it's just run on /), the urls are still generated like the app is run on /.

Is there any way to tell spring to use a base url when generating these?

Indochina answered 22/4, 2015 at 8:7 Comment(4)
The easiest is to just change your application's context path to match the public API path. A second alternative is to use something like mod_substitute to regex all of the responses.Errant
I tried setting server.contextPath="/api/", but that just made the production server serve everyhing on /api/api/...Indochina
If your context path is /api/, then apache should proxy to /api/, not to / on tomcat.Errant
I found the solution, will post below.Indochina
I
7

I've figured out my problem. Spring wasn't at fault. When building links, spring uses the X-Forwarded-Host, X-Forwarded-Ssl, etc. and, since 4.1.3, X-Forwarded-Prefix to correctly build urls that will be forwarded by a proxy. This last one however, is not automatically set by apache when proxying, so installing mod_headers and adding RequestHeader set X-Forwarded-Prefix "api"to my LocationMatch directive solved everything.

Indochina answered 22/4, 2015 at 13:49 Comment(2)
Excellent, saved me on this one big time - ty.Alwitt
I needed to add a leading slash, e.g. RequestHeader set X-Forwarded-Prefix "/api"Dibru

© 2022 - 2024 — McMap. All rights reserved.