URL Rewrite Filter 小例子(http to https)

Feb 06 2010

URL Rewrite Filter是一个很好用的url重写的小工具,他可以根据你提供的url规则进行url的重写。这里是它的主页。
使用方法很简单,首先把它提供的jar包放到你lib目录下。之后在web.xml文件中加入filter的定义。此时注意filter的顺序。

    <filter>
        <filter-name>UrlRewriteFilter</filter-name>
        <filter-class>org.tuckey.web.filters.urlrewrite.UrlRewriteFilter</filter-class>
        <init-param>
            <param-name>confPath</param-name>
            <param-value>/WEB-INF/urlrewrite.xml</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文件
它包括多种匹配方式,主要有正则表达式,wildcard,rewrite_mod等方式,下面演示的是正则表达式的方式

    <rule match-type="regex">
      <condition type="scheme" operator="equal">http</condition>
      <condition name="host" operator="equal">www.example.com</condition>
      <condition type="port" operator="notequal">443</condition>
       <from>^/(.*)$</from>
       <to>https://%{server-name}%{context-path}/$1?%{query-string}</to>
    </rule>

其中from标签就是你的url规则,to标签值的就是要重写的地址。condition是指的条件。
其中的具体参数可以参考user manual

这个例子指的就是把http请求重写为https请求。
https请求时ssl加密请求,所用端口为port。要注意防止循环转向,所以重写的条件中包括了端口不包括443.
也就是这句

<condition type="port" operator="notequal">443</condition>

而且在url中可以使用很多request或者response中的参数或者方法。比如:%{server-name}就是得到请求的域名,%{context-path}是上下文路径,%{query-string}是请求所带的参数。
而这些所对应的其实就是request.getRemoteServerName(),request.getContextPath(),request.getQueryString()方法。
具体哪些可以使用可以参考他的帮助手册

No responses yet

Leave a Reply