How to redirect http://example.com to http://www.example.com in tomcat

20,299

Solution 1

If you need server-side redirection in Tomcat from one URL to another, you have several options:

  1. Some simple redirections might be performed by Load Balancer web application shipped with Tomcat 5.5; it looks like later Tomcat releases have abandoned it.
  2. If your needs for URL redirection may be limited to web application level, then UrlRewriteFilter from www.tuckey.org is the powerful tool, most probably to help you.
  3. If your needs are better fit with server/container level redirection, then the right tool is probably the RewriteValve, a component of JBoss Web Server, comparable in power with Apache httpd mod_rewrite.
  4. If you need server-level redirection, but prefer something more light-weight, you may wish to have a look at my Tomcat Redirect Valve.

Solution 2

In Tomcat (servlets):

servletResponse.setStatus(res.SC_MOVED_TEMPORARILY);
servletResponse.setHeader("Location", "http://www.domain.com");

In JavaScript:

<script type="text/javascript">
    window.location = "http://www.domain.com"
</script>

In plain HTML:

<meta HTTP-EQUIV="REFRESH" content="0; url=http://www.domain.com">
Share:
20,299

Related videos on Youtube

Joel Coel
Author by

Joel Coel

Updated on September 17, 2022

Comments

  • Joel Coel
    Joel Coel over 1 year

    Is there a way using the virtual server tags in the server.xml file in tomcat to redirect anyone who accesses the domain directly (eg : http://example.com) to redirect them to the http://www.example.com www sub domain?

    any help would be greatly appreciated.

  • pk.
    pk. about 13 years
    He's looking for URL rewriting rules, not DNS hacks. But technically, yes, he could do this with DNS
  • Quandary
    Quandary about 13 years
    @pk: Actually, doing this in Tomcat via URL-rewriting is a hack. DNS is the proper way.