Apache的Rewrite詳解

Pam53Q 8年前發布 | 11K 次閱讀 Apache Web服務器 Apache HTTP Server

Rewrite的需求

在用Apache做web服務器的時候,有的時候需要將輸入的URL轉換成另一個URL這種需求。比如用CodeIgniter框架開發web應用的時候,我們訪問的所有路徑都要經過index.php,由這個index.php做統一路由,訪問地址如下:

example.com/index.php/news/article/my_article

這樣的地址實在是太丑了,我們想要一個干凈的地址如下:

example.com/news/article/my_article

這時你的 Apache 服務器需要啟用 mod_rewrite ,然后簡單的通過一個 .htaccess 文件再加上一些簡單的規則就可以移除URL中的 index.php 了。下面是這個文件的一個例子, 其中使用了 "否定條件" 來排除某些不需要重定向的項目:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L]

在上面的例子中,除已存在的目錄和文件,其他的 HTTP 請求都會經過你的 index.php 文件。也就是說單用戶在地址欄里輸入【 example.com/news/article/my_article 】的時候實際上訪問的是【 example.com/index.php/news/article/my_article 】。

Rewrite使用詳解

1.確認Apache是否加載了Rewrite模塊

確認配置文件httpd.conf 中是否存有下面的代碼:

Apache1.x

LoadModule rewrite_module libexec/mod_rewrite.so   
AddModule mod_rewrite.c

Apache2.x

LoadModule rewrite_module modules/mod_rewrite.so

啟用.htaccess

AllowOverride None 修改為: AllowOverride All

配置Rewrite規則

Rewrite規則可以在httpd-vhosts.conf文件和.htacess文件中進行配置。在虛擬域名配置文件下配置如下例:

NameVirtualHost *:80
<VirtualHost *:80>
    DocumentRoot "D:/wamp/www/testphp/"
    ServerName php.iyangyi.com
    ServerAlias www.pptv.cn #可省略
    ServerAdmin stefan321@qq.com #可省略
    ErrorLog logs/dev-error.log #可省略
    CustomLog logs/dev-access.log common #可省略
    ErrorDocument 404 logs/404.html #可省略
    <Directory "D:/wamp/www/testphp/">
        Options Indexes FollowSymLinks
        AllowOverride All
        Order Allow,Deny
        Allow from all
        RewriteEngine on
        RewriteCond %{REQUEST_FILENAME} !-d
        RewriteCond %{REQUEST_FILENAME} !-f
        RewriteRule ^(.*)$ index.php/$1 [QSA,PT,L]
    </Directory>
</VirtualHost>

如果在.htacess文件下配置,可以具體配置到訪問某個目錄下URL的重定向規則。

RewriteCond 與 RewriteRule

學習Rewrite只需要重點了解他的三個核心就可以: RewriteEngineRewriteCondRewriteRule

RewriteEngine

這個是rewrite功能的總開關,用來開啟是否啟動url rewrite

RewriteEngine on

RewriteCond

RewriteCond就是一個過濾條件,簡單來說,當URL滿足RewriteCond配置的條件的情況,就會執行RewriteCond下面緊鄰的RewriteRule語句。

RewriteCond的格式如下:

RewriteCond %{待測試項目} 正則表達式條件

舉個例子:

RewriteEngine on
RewriteCond  %{HTTP_USER_AGENT}  ^Mozilla//5/.0.*
RewriteRule  index.php            index.m.php

如果設置上面的匹配規則,到來的http請求中的HTTP_USER_AGENT匹配【^Mozilla//5/.0.*】正則表達式的話,則執行下面的RewriteRule,也就是說訪問路徑會跳轉到 index.m.php這個文件。

調試

在apache的配置文件中加入下面配置:

#Rewrite Log 
RewriteLog logs/rewrite.log #此處可以寫絕對地址 
RewriteLogLevel 3

這樣就可以在Apache的默認日志文件中找到rewrite.log觀察apache URL重寫的過程。

 

來自:http://www.jianshu.com/p/103742cccaff

 

 本文由用戶 Pam53Q 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!