如果您只想更改picture.php 的路由,那么在.htaccess 中添加重写规则将满足您的需求,但是,如果您想像在 Wordpress 中那样重写 URL,那么 PHP 是一种方式。这是一个简单的例子。
文件夹结构
根文件夹中有两个文件,.htaccess 和 index.php,最好将其余的 .php 文件放在单独的文件夹中,例如 inc/。
root/
inc/
.htaccess
index.php
.htaccess
RewriteEngine On
RewriteRule ^inc/.*$ index.php
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php [QSA,L]
这个文件有四个指令:
-
RewriteEngine - 启用重写引擎
-
RewriteRule - 拒绝访问 inc/ 文件夹中的所有文件,将对该文件夹的任何调用重定向到 index.php
-
RewriteCond - 允许直接访问所有其他文件(如图像、css 或脚本)
-
RewriteRule - 将其他任何内容重定向到 index.php
index.php
因为现在一切都重定向到index.php,所以会判断url是否正确,所有参数是否存在,参数类型是否正确。
要测试 url,我们需要有一套规则,而最好的工具就是正则表达式。通过使用正则表达式,我们将一击杀死两只苍蝇。 Url,要通过此测试,必须具有在允许字符上测试的所有必需参数。以下是一些规则示例。
$rules = array(
'picture' => "/picture/(?'text'[^/]+)/(?'id'\d+)", // '/picture/some-text/51'
'album' => "/album/(?'album'[\w\-]+)", // '/album/album-slug'
'category' => "/category/(?'category'[\w\-]+)", // '/category/category-slug'
'page' => "/page/(?'page'about|contact)", // '/page/about', '/page/contact'
'post' => "/(?'post'[\w\-]+)", // '/post-slug'
'home' => "/" // '/'
);
接下来是准备请求的uri。
$uri = rtrim( dirname($_SERVER["SCRIPT_NAME"]), '/' );
$uri = '/' . trim( str_replace( $uri, '', $_SERVER['REQUEST_URI'] ), '/' );
$uri = urldecode( $uri );
现在我们有了请求 uri,最后一步是根据正则表达式规则测试 uri。
foreach ( $rules as $action => $rule ) {
if ( preg_match( '~^'.$rule.'$~i', $uri, $params ) ) {
/* now you know the action and parameters so you can
* include appropriate template file ( or proceed in some other way )
*/
}
}
成功的匹配将,因为我们在正则表达式中使用命名子模式,填充$params 数组几乎与PHP 填充$_GET 数组相同。但是,当使用动态 url 时,$_GET 数组会被填充而无需任何参数检查。
/图片/一些+文字/51
大批
(
[0] => /图片/一些文字/51
[文本] => 一些文本
[1] => 一些文字
[id] => 51
[2] => 51
)
图片.php?text=some+text&id=51
大批
(
[文本] => 一些文本
[id] => 51
)
这几行代码和对正则表达式的基本了解足以开始构建可靠的路由系统。
完整来源
define( 'INCLUDE_DIR', dirname( __FILE__ ) . '/inc/' );
$rules = array(
'picture' => "/picture/(?'text'[^/]+)/(?'id'\d+)", // '/picture/some-text/51'
'album' => "/album/(?'album'[\w\-]+)", // '/album/album-slug'
'category' => "/category/(?'category'[\w\-]+)", // '/category/category-slug'
'page' => "/page/(?'page'about|contact)", // '/page/about', '/page/contact'
'post' => "/(?'post'[\w\-]+)", // '/post-slug'
'home' => "/" // '/'
);
$uri = rtrim( dirname($_SERVER["SCRIPT_NAME"]), '/' );
$uri = '/' . trim( str_replace( $uri, '', $_SERVER['REQUEST_URI'] ), '/' );
$uri = urldecode( $uri );
foreach ( $rules as $action => $rule ) {
if ( preg_match( '~^'.$rule.'$~i', $uri, $params ) ) {
/* now you know the action and parameters so you can
* include appropriate template file ( or proceed in some other way )
*/
include( INCLUDE_DIR . $action . '.php' );
// exit to avoid the 404 message
exit();
}
}
// nothing is found so handle the 404 error
include( INCLUDE_DIR . '404.php' );