1、Rewrite規則簡介: Rewirte主要的功能就是實現URL的跳轉,它的正則表達式是基於Perl語言。可基於服務器級的(httpd.conf)和目錄級的 (.htaccess)兩種方式進行設置。 2、在Apache配置中啓用Rewrite 打開配置文件httpd.conf:php
**1.啓用rewrite** # LoadModule rewrite_module modules/mod_rewrite.so 去除前面的 # 2.啓用.htaccess 在虛擬機配置項中 AllowOverride None 修改成: AllowOverride All //讓apache服務器支持.htaccess
也能夠直接在http.conf 中配置html
<VirtualHost *:8080> ServerAdmin webmaster@dummy-host2.example.com DocumentRoot "D:/phpwin/wamp/www/yktadmin/public" ServerName qrcodepay.com ErrorLog "logs/dummy-host2.example.com-error.log" CustomLog "logs/dummy-host2.example.com-access.log" common <Directory "D:/phpwin/wamp/www/yktadmin/public"> Options FollowSymLinks ExecCGI AllowOverride All Order allow,deny Allow from all Require local RewriteEngine on RewriteCond %{REQUEST_FILENAME} !-f RewriteCond ${REQUEST_FILENAME} !-d RewriteRule ^(.*)$ index.php/$1 [QSA,PT,L] </Directory> </VirtualHost>
2、Rewrite基本寫法 服務器有配置文件不可能由咱們來改,因此大多狀況下要在網站的根目錄下建一個.htaccess文件。 代碼以下web
RewriteEngine on //啓動rewrite引擎 RewriteRule ^/index([0-9]*).html$ /index.php?id=$1 //「([0-9]*)」 表明範圍 用(.*)表明全部,下同。 RewriteRule ^/index([0-9]*)/$ /index.php?id=$1 [R] //虛擬目錄
4.rewrite規則學習
在新建.htaccess文件以後,就在裏面寫入如下內容: RewriteEngine on #rewriteengine 爲重寫引擎開關on爲開啓off爲關閉 RewriteRule ([0-9]{1,})$index.php?id=$1 在這裏,RewriteRule是重寫規則,是用正則表達式的句子, ([0-9]{1,})表示由數字組成的,$表示結束標誌,表示以數字結束!若是要實現僞靜態頁面,規則以下: RewriteEngine on RewriteRule ([a-zA-Z]{1,})-([0-9]{1,}).html$index.php?action=$1&id=$2 在爲個正則表達式中, ([a-zA-Z]{1,})-([0-9]{1,}).html$是規則,正則表達式
index.php?action=$1&id=$2是要替換的格式,$1表明第1括號匹配的值,$2表明第二個括號的值,如此類推! 測試PHP腳本以下: index.php文件中的代碼以下: echo ‘你的Action值爲:’ . $_GET['action']; echo ‘ ’; echo ‘ID值爲:’ . $_GET['id']; ?>apache
在瀏覽器地址欄輸入: localhost/page-18.html 輸出的是: 你的Action值爲:page ID值爲:18api
3、Apache mod_rewrite規則重寫的標誌一覽瀏覽器
RewriteEngine On RewriteCond %{HTTP_HOST} ^www.jb51.net RewriteCond %{REQUEST_URI} !^user.php$ RewriteCond %{REQUEST_URI} .php$ RewriteRule (.*).php$ http://www.jb51.net/$1/ [R] RewriteCond %{HTTP_HOST} !^www.jb51.net RewriteRule ^(.+) %{HTTP_HOST} [C] RewriteRule ^([^.]+).jb51.net http://www.jb51.net/user.php?username=$1
例子二服務器
/type.php?typeid=* –> /type*.html /type.php?typeid=*&page=* –> /type*page*.html RewriteRule ^/type([0-9]+).html$ /type.php?typeid=$1 [PT] RewriteRule ^/type([0-9]+)page([0-9]+).html$ /type.php?typeid=$1&page=$2 [PT]