Closed crearo closed 6 years ago
Okay, returned a simple JS response. window.location = "http://new-website.com";
Reply with a 3xx HTTP code, containing a "Location" header pointing where you want.
I don't really want to come off as rude or snarky but maybe you should learn how the HTTP protocol works before going too deep with web projects. Just my 2 cents, honestly, from a guy who spent the best part of a decade bashing his head against walls needlessly.
Thanks! I actually did so. Is this how you'd do it?
/**
* Redirects user to {@param urlToRedirectTo}
*/
public static Response newRedirectResponse(String urlToRedirectTo) {
return newFixedLengthResponse(Status.TEMPORARY_REDIRECT, "text/html",
"<!DOCTYPE html>\n" +
"<html>\n" +
"<head>\n" +
"<title>Redirect</title>\n" +
"<script type=\"text/javascript\">\n" +
"window.location = " + "\"" + urlToRedirectTo + "\"" + ";\n" +
"</script>\n" +
"</head>\n" +
"</html>");
}
No. You don't write the body on a 3xx response. Instead you send a "Location" header with the URL you want the browser to go to, like I stated above.
Thanks. Just thought it was odd this SO post had so many upvotes for doing the above.
Also, was thinking, I've seen several well-known websites show a 2 second long You are being redirected to www.xyz.com
before redirecting you there. Haven't checked whether the response code is in 3XX there, but that makes sense to me; the user should be told that they're being redirected.
It isn't. If the redirect is done with a 3xx HTTP code, the browser doesn't render anything, instead, it will fetch the URL in the Location header from the response and try to render that instead. However, if the URL in the Location header also returns a 3xx it will again not render and fetch a new URL. Browsers will do this a limited number of times, after which they will stop attempting to fetch pages and show a "Too Many Redirects" error.
If a 3xx response doesn't have a Location header the browser doesn't properly redirect (because it doesn't know where it's supposed to go next) so instead it will attempt to render the response body if there is one. This type of HTTP code misuse can be used to make fools of web crawlers and attack tools, however I don't recommend anyone but the most advanced protocol users to use such tricks as it can severely damage the way the website works (and with 3xx codes that damage can be permanent).
Makes sense, thanks!
From the
get
ofRouterNanoHTTPD.DefaultHandler
I'd like to redirect the user if a certain condition is met (for eg, isn't validated). How would I do that?