Apache Mod_Rewrite 教程
Apache Mod_Rewrite 是一个强大的模块,用于修改服务器端的请求。它可以让你重写 URL,使你的网站更加用户友好,同时也可以用于 SEO 优化。
基本用法
安装 Mod_Rewrite 模块 首先,确保你的 Apache 服务器已经安装了 Mod_Rewrite 模块。
sudo a2enmod rewrite sudo systemctl restart apache2
配置 .htaccess 文件 在网站的根目录下创建或编辑 .htaccess 文件。
RewriteEngine On
重写规则 使用 RewriteRule 命令来定义重写规则。
RewriteRule ^old-url$ new-url [L,R=301]
这条规则会将
old-url
重写到new-url
,并且返回 301 重定向。
实用案例
SEO 优化 将动态 URL 重写到静态 URL,有助于搜索引擎优化。
RewriteRule ^articles/([0-9]+)/$ /article.php?id=$1 [L]
路径简化 简化复杂的 URL,使其更易于记忆。
RewriteRule ^news/latest$ /news/latest-news.html [L]
路径重定向 将一个路径重定向到另一个路径。
RewriteRule ^old-path$ /new-path [R=301,L]
注意事项
- 确保
.htaccess
文件权限正确,否则 Apache 服务器无法读取它。 - 仔细检查重写规则,避免产生无限循环或 404 错误。
Apache Mod_Rewrite
更多信息,请访问我们的 Apache Mod_Rewrite 模块教程。