tomcat配置url重定向

2017/01/01 中间件

       SEO需求要把不带www的域名一直跳带www,因为使用的是阿里云的slb服务,且没有像nginx rewriter功能,而且也无法像apache那样通过配置.htaccess来实现或者nginx反向代理来。如果想要把不带“www’的域名重定向到带”www”域名下,又不想写代码,可以使用UrlRewriteFilter来实现。

一、简介

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

二、下载

下载UrlRewriteFilter

wget http://urlrewritefilter.googlecode.com/files/urlrewritefilter-4.0.3.jar 并放入tomcat的 WEB-INF/lib下

三、配置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>

我的配置:

<!--301地址重定向-->
  <filter>
  <filter-name>UrlRewriteFilter</filter-name>
  <filter-class>org.tuckey.web.filters.urlrewrite.UrlRewriteFilter</filter-class>
  <init-param>
<param-name>confReloadCheckInterval</param-name>
<param-value>60</param-value>
</init-param>
   <init-param>
<param-name>confPath</param-name>
<param-value>/WEB-INF/urlrewite.xml</param-value>
</init-param>
  <init-param>
<param-name>logLevel</param-name>
<param-value>DEBUG</param-value>
</init-param>
  <init-param>
<param-name>statusPath</param-name>
<param-value>/status</param-value>
</init-param>
  <init-param>
<param-name>statusEnabled</param-name>
<param-value>true</param-value>
</init-param>
  
</filter>
<filter-mapping>
  <filter-name>UrlRewriteFilter</filter-name>
  <url-pattern>/*</url-pattern>
  <dispatcher>REQUEST</dispatcher>
  <dispatcher>FORWARD</dispatcher>
</filter-mapping>

四、添加跳转规则

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

<urlrewrite>
<rule>
  <name>seo redirect</name>
  <!-- 排除 -->
  <condition name="host" operator="notequal">^www.bighug.top</condition>
  <condition name="host" operator="notequal">^localhost</condition>
  <!--规则 -->
  <from>^/(.*)</from>
  <to type="permanent-redirect" last="true">http://www.bighug.top/$1</to>
 </rule>
</urlrewrite>

五、测试

访问 http://bighug.top 跳转到http://www.bighub.top 就配置成功了

参考官方文档:

http://cdn.rawgit.com/paultuckey/urlrewritefilter/master/src/doc/manual/4.0/index.html

Search

    Table of Contents