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]