系統內容:Windows Apache 2.2
載入Rewrite模組:
在conf目錄下httpd.conf中找到
代碼如下 |
複製代碼 |
LoadModule rewrite_module modules/mod_rewrite.so
|
這句,去掉前邊的注釋符號“#”,或添加這句。
允許在任何目錄中使用“.htaccess”檔案,將“AllowOverride”改成“All”(預設為“None”):
代碼如下 |
複製代碼 |
# AllowOverride controls what directives may be placed in .htaccess files. # It can be “All”, “None”, or any combination of the keywords: # Options FileInfo AuthConfig Limit # AllowOverride All
|
在Windows系統下不能直接建立“.htaccess”檔案,可以在命令列下使用“echo a> .htaccess”建立,然後使用記事本編輯。
Apache Rewrite模組的簡單應用:
Rewrite的所有判斷規則均基於Perl風格的Regex,通過以下基礎樣本能寫出符合自己跳轉需求的代碼。
1、請求跳轉
目的是如果請求為.jsp檔案,則跳轉至其它網域名稱訪問。
例如:訪問111cn.net /a.php跳轉至www.111cn.net /b.php網頁,訪問111cn.net /news/index.php跳轉至www.111cn.net /news/index.php網頁
注意:不是使用HTML技術中的meta或者javascript方式,因為111cn.net /a.php這個檔案並不存在,用的是Apache2.2伺服器中的Rewrite模組。
修改 .htaccess或apche的設定檔httpd.conf檔案,添加以下內容
代碼如下 |
複製代碼 |
RewriteEngine on #開啟Rewrite模組 RewriteRule (.*).php$ http://www.111cn.net /$1.jsp [R=301,L,NC]
|
#截獲所有.jsp請求,跳轉到http://www.111cn.net /加上原來的請求再加上.php。R=301為301跳轉,L為rewrite規則到此終 止,NC為不區分大小寫
2、網域名稱跳轉
如果請求為old.mrlon.net下的所有URL,跳轉至www.111cn.net
代碼如下 |
複製代碼 |
RewriteEngine on #開啟Rewrite模組 RewriteCond %{REMOTE_HOST} ^old.studenthome.cn$ [NC] #針對host為old.mrlon.net的主機做處理,^為開始字元,$為結尾字元 RewriteRule (.*) http://www.111cn.net /$1 [R=301,L,NC]
|
3、防盜鏈
如果本網站的圖片不想讓其它網站調用,可以在 .htaccess或者apche的設定檔httpd.conf檔案中添加以下內容
代碼如下 |
複製代碼 |
RewriteEngine on #開啟Rewrite模組 RewriteCond %{HTTP_REFERER} !^$ #如果不是直接輸入圖片地址 RewriteCond %{HTTP_REFERER} !img.mrlon.net$ [NC] #且如果不是img.mrlon.net所有子網域名稱調用的 RewriteCond %{HTTP_REFERER} !img.mrlon.net/(.*)$ [NC] RewriteCond %{HTTP_REFERER} !zhuaxia.com [NC] RewriteCond %{HTTP_REFERER} !google.com [NC] RewriteCond %{HTTP_REFERER} !google.cn [NC] RewriteCond %{HTTP_REFERER} !baidu.com [NC] RewriteCond %{HTTP_REFERER} !feedsky.com [NC] RewriteRule (.*).(jpg|jpeg|jpe|gif|bmp|png|wma|mp3|wav|avi|mp4|flv|swf)$ /err.jpg [R=301,L,NC]
|
#截獲所有.jpg或.jpeg……請求,跳轉到/err.jpg提示錯誤的圖片,註:該圖片不能在原網域名稱下,也不 能在該.htaccess檔案有效控制的檔案夾中
4、不需要定義.htaccess檔案
在Apache2confhttpd.conf 最後一行添加
代碼如下 |
複製代碼 |
RewriteEngine On RewriteRule ^(.*)-htm-(.*)$ $1.php?$2 |