URL重写通过.htaccess将复杂URL转换为简洁友好的形式,需启用mod_rewrite模块,配置RewriteRule规则,使如news/123映射到index.php?module=news&action=view&id=123,并在PHP中解析$_GET参数加载对应控制器,提升SEO和用户体验。

URL重写,简单来说,就是把一个复杂的、不利于用户记忆和搜索引擎抓取的URL,变成一个更简洁、更友好的URL。在PHP项目中,这通常通过服务器的配置来实现,最常见的就是利用Apache的
.htaccess
URL重写的核心在于告诉服务器,当用户访问某个“友好”URL时,实际上应该执行哪个PHP脚本,并传递哪些参数。
解决方案
要实现URL重写,你需要以下几个步骤:
立即学习“PHP免费学习笔记(深入)”;
启用Apache的mod_rewrite
a2enmod rewrite
创建或修改.htaccess
.htaccess
编写重写规则:在
.htaccess
RewriteEngine
RewriteCond
RewriteRule
一个简单的例子:
假设你有一个URL:
index.php?module=news&action=view&id=123
news/123
那么,你的
.htaccess
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^news/([0-9]+)$ index.php?module=news&action=view&id=$1 [L]解释一下:
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-fRewriteCond %{REQUEST_FILENAME} !-dRewriteRule ^news/([0-9]+)$ index.php?module=news&action=view&id=$1 [L]
^news/([0-9]+)$
news/
([0-9]+)
index.php?module=news&action=view&id=$1
$1
[L]
index.php
$_GET
<?php $module = $_GET['module'] ?? 'home'; // 默认模块 $action = $_GET['action'] ?? 'index'; // 默认动作 $id = $_GET['id'] ?? null; // ID // 根据模块和动作来加载相应的控制器和方法 // 例如: $controllerName = ucfirst($module) . 'Controller'; $actionName = $action . 'Action'; // 加载控制器类 require_once 'controllers/' . $controllerName . '.php'; // 创建控制器实例 $controller = new $controllerName(); // 调用控制器方法 $controller->$actionName($id); ?>
这段代码首先从
$_GET
module
action
id
对于更复杂的URL结构,你可以编写更多的
RewriteRule
products/category/123
RewriteRule ^products/category/([0-9]+)$ index.php?module=products&action=category&id=$1 [L]
关键在于理解
RewriteRule
.htaccess
.htaccess
URL重写可以使你的URL更简洁、更易于理解,这有助于提高你的网站在搜索引擎中的排名。搜索引擎更喜欢结构清晰、语义化的URL。此外,友好的URL也更容易被用户分享和记忆。
PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号