關於urlrewrite
urlrewrite使用強大的自定義規則來使用用戶更容易記住、搜索引擎更容易找到的URL(對於seo比較重要)。通過使用規則模板、重寫映射,Web管理員可以輕松地設置規則,根據HTTP標頭、HTTP響應或請求標頭、變量,甚至復雜的編程規則來定義URL重寫行為。此外,Web管理員可以根據重寫規則中表示的邏輯進行url重定向、發送自定義響應或停止HTTP請求。
為何有這篇教程
百度上查詢urlrewrite這個工具包的使用教程時,網上並沒有springboot整合的完整示例,於是就自己摸索的寫了一下。
開始:
1.引入maven依賴:
<dependency> <groupId>org.tuckey</groupId> <artifactId>urlrewritefilter</artifactId> <version>4.0.4</version> </dependency>
2.重寫UrlRewriteFilter的過濾器加載urlrewrite.xml規則,urlrewrite.xml放在 resources文件夾下
package webapp.conf;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;
import org.tuckey.web.filters.urlrewrite.Conf;
import org.tuckey.web.filters.urlrewrite.UrlRewriteFilter;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import java.io.IOException;
@Configuration
public class UrlRewriteConf extends UrlRewriteFilter {
private static final String URL_REWRITE = "classpath:/urlrewrite.xml";
//注入urlrewrite配置文件
@Value(URL_REWRITE)
private Resource resource;
//重寫配置文件加載方式
protected void loadUrlRewriter(FilterConfig filterConfig) throws ServletException {
try {
//將Resource對象轉換成Conf對象
Conf conf = new Conf(filterConfig.getServletContext(), resource.getInputStream(), resource.getFilename(), "@@traceability@@");
checkConf(conf);
} catch (IOException ex) {
throw new ServletException("Unable to load URL rewrite configuration file from " + URL_REWRITE, ex);
}
}
}
3.urlrewrite.xml文件配置,urlrewrite.xml規則示例:
<?xml version="1.0" encoding="utf-8"?> <!DOCTYPE urlrewrite PUBLIC "-//tuckey.org//DTD UrlRewrite 3.2//EN" "http://tuckey.org/res/dtds/urlrewrite3.2.dtd"> <urlrewrite> <rule> <name>seo redirect 301</name> <condition name="host">^9191boke.com$</condition> <from>^/(.*)</from> <to type="permanent-redirect" last="true">http://www.9191boke.com/$1</to> </rule> <rule> <name>seo redirect 301</name> <condition name="host">^localhost:9191$</condition> <from>^/(.*)</from> <to type="permanent-redirect" last="true">http://www.localhost:9191/$1</to> </rule> <rule> <from>^/([0-9]+).html$</from> <to>/blogdetails/$1.html</to> </rule> <rule> <from>^/p_([0-9]+).html$</from> <to>/?page=$1</to> </rule> </urlrewrite>
from標簽內的表示匹配的模式,<to>標簽內的是想要轉換的模式。
<rule>
<name>seo redirect 301</name>
<condition name="host">^9191boke.com$</condition>
<from>^/(.*)</from>
<to type="permanent-redirect" last="true">http://www.9191boke.com/$1</to>
</rule>
以上為域名301重定向,所有http(s)://9191boke.com/xxx鏈接會重定向至http://www.9191boke.com/xxx
<from>^/([0-9]+).html$</from>
<to>/blogdetails/$1.html</to>
^/([0-9]+).html$表示http://xxx/數字.html會發送實際請求為http://xxx/blogdetails/數字.html
<rule>
<from>^/p_([0-9]+).html$</from>
<to>/?page=$1</to>
</rule>
^/p_([0-9]+).html$表示http://xxx/p_數字.html會發送實際請求為http://xxx/?page=數字.html
每一條攔截規則使用rule標簽包裹。
這里沒有特別需要注意的地方,如果只是簡單的使用的話,記住下面這一點就足夠了。
如果你會用正則表達式的話,可以通過正則表達式來處理(推薦使用),如果不會,可以使用通配符。