URL Rewrite Filter 小例子(http to https)

Feb 06 2010 Published by Tony under Java

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

Resin中配置URL重写

Jan 30 2010 Published by Tony under Java

web项目中url rewright的功能是一个很常见得功能,实现的方式多种多http://ohacker.com/wp-admin/post-new.php样,最常见的莫过于在web服务器中设置,例如在Apache中设置。而如果你使用Java开发,那么还有个更多的方案供你选择如使用url rewrite filter ,而如果你是使用resin(版本需要>3.1)作为你的application server,那么你还可以使用resin自带的url 重写功能。

首先,你必须使用resin-web.xml代替常规的web.xml作为你的项目部署描述文件,其次,你需要在描述文件中指定一个url重写的配置文件。再在这个文件中配置。

resin-web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://caucho.com/ns/resin"
         xmlns:resin="http://caucho.com/ns/resin/core">
 
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
  <rewrite-dispatch>
     <import path='WEB-INF/rewrite.xml'/>
  </rewrite-dispatch>
</web-app>

rewrite.xml

<rewrite-dispatch xmlns="http://caucho.com/ns/resin"
	xmlns:resin="http://caucho.com/ns/resin/core">
	<redirect regexp="^/tst" target="https://ohacker.com/tst">
		<when secure="false" />
	</redirect>
</rewrite-dispatch>

No responses yet