tomcat默认情况下不带www的域名是不会跳转到带www的域名的,而且也无法像apache那样通过配置.htaccess来实现。如果想要把不带“www’的域名重定向到带”www”域名下,又不想写代码,可以使用UrlRewriteFilter来实现。

1.简介

urlRewriteFilter是一个用于改写URL的Web过滤器,类似于Apache的mod_rewrite。适用于任何Web应用服务器(如 Tomcat,jboss,jetty,Resin,Orion等)。其典型应用就把动态URL静态化,便于搜索引擎爬虫抓取你的动态网页。

2.下载

下载UrlRewriteFilter

wget http://urlrewritefilter.googlecode.com/files/urlrewritefilter-4.0.3.jar

并放入tomcat的 WEB-INF/lib下

3.配置tomcat

编辑WEB-INF/web.xml 在其它servlet mapping前加入


  <filter-name>UrlRewriteFilter</filter-name>
  <filter-class>org.tuckey.web.filters.urlrewrite.UrlRewriteFilter</filter-class>
</filter>
<filter-mapping>
  <filter-name>UrlRewriteFilter</filter-name>
  <url-pattern>/*</url-pattern>
  <dispatcher>REQUEST</dispatcher>
  <dispatcher>FORWARD</dispatcher>
</filter-mapping>" data-snippet-id="ext.d9335c889eb8c29f7d0586484daf2dcb" data-snippet-saved="false" data-codota-status="done">&lt;filter&gt;
  &lt;filter-name&gt;UrlRewriteFilter&lt;/filter-name&gt;
  &lt;filter-class&gt;org.tuckey.web.filters.urlrewrite.UrlRewriteFilter&lt;/filter-class&gt;
&lt;/filter&gt;
&lt;filter-mapping&gt;
  &lt;filter-name&gt;UrlRewriteFilter&lt;/filter-name&gt;
  &lt;url-pattern&gt;/*&lt;/url-pattern&gt;
  &lt;dispatcher&gt;REQUEST&lt;/dispatcher&gt;
  &lt;dispatcher&gt;FORWARD&lt;/dispatcher&gt;
&lt;/filter-mapping&gt;

4.添加跳转规则

在WEB-INF下新建urlrewite.xml文件,加入跳转规则


  <rule>
      <name>seo redirect</name>
      <condition name=&quot;host&quot; operator=&quot;notequal&quot;>^www.example.com</condition>
      <condition name=&quot;host&quot; operator=&quot;notequal&quot;>^localhost</condition>
      <from>^/(.*)</from>
      <to type=&quot;permanent-redirect&quot; last=&quot;true&quot;>http://www.example.com/$1</to>
  </rule>
</urlrewrite>" data-snippet-id="ext.8be7c6714e65fa3f79b0e1c6c6215563" data-snippet-saved="false" data-codota-status="done">&lt;urlrewrite&gt;
  &lt;rule&gt;
      &lt;name&gt;seo redirect&lt;/name&gt;
      &lt;condition name="host" operator="notequal"&gt;^www.example.com&lt;/condition&gt;
      &lt;condition name="host" operator="notequal"&gt;^localhost&lt;/condition&gt;
      &lt;from&gt;^/(.*)&lt;/from&gt;
      &lt;to type="permanent-redirect" last="true"&gt;http://www.example.com/$1&lt;/to&gt;
  &lt;/rule&gt;
&lt;/urlrewrite&gt;

参考文章

http://nematodes.org/martin/2010/02/04/301-permanent-redirect-with-tomcat-howto/

http://tuckey.org/urlrewrite/