Wednesday, June 18, 2003

Fixing the Tomcat 302 Redirect Issue


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

Tomcat sends a redirect to the browser to make them go to: or
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.


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
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
request.getRequestDispatcher(redirectPath).forward(request, response);

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





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

Now restart tomcat and that should be it.