URL redirection in Java return 302 instead of 301

Randomize picture Randomize · Jan 6, 2012 · Viewed 17.8k times · Source

I'm using this code to redirect url:

  response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
  response.sendRedirect(newURL);

what I can see is a correct redirection but the value returned in the response is 302 instead of 301. How can I force it to 301?

Answer

JB Nizet picture JB Nizet · Jan 6, 2012

If you use sendRedirect, it will reset the status to 302. You'll have to use setHeader to set the Location header yourself to redirect using a 301 status.

Example code:

response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
response.setHeader("Location", "http://somewhere/");

Pulled from this answer: HttpServletResponse sendRedirect permanent