Spring MVC "redirect:" prefix always redirects to http -- how do I make it stay on https?

Viewed 51943

I solved this myself, but I spent so long discovering such a simple solution, I figured it deserved to be documented here.

I have a typical Spring 3 MVC setup with an InternalResourceViewResolver:

<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
  <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
  <property name="prefix" value="/" />
  <property name="suffix" value=".jsp" />
</bean>

I have a pretty simple handler method in my controller, but I've simplified it even more for this example:

@RequestMapping("/groups")
public String selectGroup() {
    return "redirect:/";
}

The problem is, if I browse to https://my.domain.com/groups, I end up at http://my.domain.com/ after the redirect. (In actuality my load-balancer redirects all http requests to https, but this just causes multiple browser alerts of the type "You are leaving/entering a secure connection" for folks who have such alerts turned on.)

So the question is: how does one get spring to redirect to https when that's what the original request used?

9 Answers

What worked for me is adding this to application.properties server.tomcat.use-relative-redirects=true

So when you have:

public function redirect() {
  return "redirect:/"
}

Without the server.tomcat.use-relative-redirects it will add a Location header like: http://my-host.com/. With the server.tomcat.use-relative-redirects it will look like: /. So it will be relative to the current page from browser perspective.

Since Spring Boot 2.1 you have to add the following configuration to your application.properties:

server.use-forward-headers=true 

or application.yml:

server:
  use-forward-headers: true

if you use springmvc ,you can try the following:

modelAndView.setView(new RedirectView("redirect url path", true, false));

I add scheme="https" in file server.xml for connector with port="80":

<Connector port="80" protocol="HTTP/1.1" URIEncoding="UTF-8"
connectionTimeout="20000" redirectPort="443" scheme="https" />

I was also facing same issue...When redirecting it goes to http instead of HTTPS , below changes done :

RedirectView redirect = new RedirectView("/xyz",true);
redirect.setExposeModelAttributes(false);
redirect.setHttp10Compatible(false);
mav = new ModelAndView(redirect);
Related