认识Apache重写模块
上几个案例说明apache是如何重写的
一、在项目入口文件同级目录创建如下三个文件
文件1 .htaccess
RewriteEngine On
RewriteRule test.html test.php
文件2 test.php
<?php
print_r($_REQUEST);
文件3 test.html
html
二、参数说明
RewriteEngine
打开或关闭重写引擎 参数 On|Off
RewriteEngine On
RewriteRule
建立一条重写规则
参数
Pattern 正则表达式,用以匹配当前的URL
Substitution 重写模板,作用是当原始URL与Pattern相匹配时,用来替换的字符串
RewriteRule Pattern Substitution [flags]
3.RewriteCond
定义重写发生的条件
%{REQUEST_FILENAME} 表示服务器变量,请求相匹配的本地文件系统的文件路径名
!-d 表示判断是否不是一个目录(文件夹)
!-f 表示判断是否不是一个文件
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
三、重写案例
- 把访问index.html重写到index.php
RewriteRule test.html test.php
- 把访问test8.html重写到访问test.php?id=8
RewriteRule ^test([0-9]*).html$ test.php?id=$1
打印输出
- 把访问test-1-3.html,重写到test.php?pid=1&id=3
RewriteRule ^test-([a-zA-Z0-9\-]+)-([0-9]+)\.html$ test.php?pid=$1&id=$2
打印输出
- 把访问 test5,重写到 test.php?id=5
RewriteRule ^test([0-9]+)$ test.php?id=$1
输出
- 把访问 test.test/c19/a255.html,定向到 test.test/test.php?category=19&article=255
RewriteRule ^c([0-9]+)/a([0-9]+)\.html$ test.php?category=$1&article=$2
打印参数
括号在正则中表示一个闭包匹配,用$加数字引用。
例如,第一个()括号,用$1引用,第二个()括号,用$2引用,以此递增
- 隐藏入口文件 index.php
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule . index.php