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> <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>
4.添加跳轉規則
在WEB-INF下新建urlrewite.xml文件,加入跳轉規則
<urlrewrite> <rule> <name>seo redirect</name> <condition name="host" operator="notequal">^www.example.com</condition> <condition name="host" operator="notequal">^localhost</condition> <from>^/(.*)</from> <to type="permanent-redirect" last="true">http://www.example.com/$1</to> </rule> </urlrewrite>
參考文章
http://nematodes.org/martin/2010/02/04/301-permanent-redirect-with-tomcat-howto/
http://tuckey.org/urlrewrite/