Wednesday, June 18, 2003

Fixing the Tomcat 302 Redirect Issue

Introduction

This problem has to do with Tomcat redirecting people to a different
page when entering a url like:


http://www.spaceprogram.com or http://www.spaceprogram.com/



Tomcat sends a redirect to the browser to make them go to:


http://www.spaceprogram.com/index.jsp or http://www.spaceprogram.com/index.html
or whatever the default page is.


When what should happen is an internal forward so the browser doesn't
get redirected. This affects search engine crawling (some will stop at
the first sign of a redirect on a sites main page).


Intended Audience

This document is for programmers that can look through source code and
compile. If there is enough need, we may be able to post already compiled
downloads on this page, but we'll see in time.


Instructions


There are 2 ways we can accomplish this, one is to subscribe to the tomcat-dev
mailing list
and beg for them to add this very simple fix. The other
is to do it yourself and follow the instructions below.


NOTE: This was done in Tomcat 4.1.18 so may need to be modified a bit
for different versions.

Also tried in 4.1.27 and it works fine - Aug. 18, 2003.


You will need to download the tomcat source distribution or get it from
cvs. The Tomcat homepage is here.



These steps apply to org.apache.catalina.servlets.DefaultServlet. After
you're done making changes, you can simply take the newly compiled version
of DefaultServlet and put it in a non source tomcat release under the
CATALINA_HOME/server/classes directory.


1. Add New Variable


/**

* for forwarding instead of redirecting on 300 errors ie: when www.x.com
is sent, instead

* of doing redirect, it will just change the response.

* TR


*/

private boolean redir301 = true;


2. Then down in init(), added this:


/**

* added this too

* TR


*/

try {

value = getServletConfig().getInitParameter("redir301");

redir301 = (new Boolean(value)).booleanValue();

} catch (Throwable t) {


;

}


3. Then in serveResource() changed to this, find where the first
line is then see what I did.




ResourceInfo welcomeFileInfo = checkWelcomeFiles(path, resources);
if (welcomeFileInfo != null) {
String redirectPath = welcomeFileInfo.path;

if(redir301){ // added TR
String contextPath = request.getContextPath();
if ((contextPath != null) && (!contextPath.equals("/"))) {
redirectPath = contextPath + redirectPath;
}
}

redirectPath = appendParameters(request, redirectPath);

/**
* Changed this for 301 stuff
* TR
*/
if(redir301){
response.sendRedirect(redirectPath);
}
else{
request.getRequestDispatcher(redirectPath).forward(request, response);
}
return;
}


4. Add new param to web.xml in catalina_home/conf/web.xml under
default servlet.



<init-param>

<param-name>redir301</param-name>

<param-value>false</param-value>

</init-param>



You must set this to false or else it will just act the same as before.


Now restart tomcat and that should be it.