apache实现博客伪静态需三步:启用mod_rewrite模块、配置allowoverride all允许.htaccess生效、在.htaccess中编写rewriterule规则,如将/post.php?id=123重写为/post/123/。

Apache 实现博客伪静态,核心是把类似 /post.php?id=123 这样的动态链接,变成更友好、更利于 SEO 的格式,比如 /post/123/ 或 /2024/05/my-first-post.html。整个过程分三步走:确保模块可用、允许规则覆盖、编写精准重写规则。
确认 mod_rewrite 已启用
这是前提。没开启这个模块,.htaccess 里的所有规则都无效。
- Linux(如 Ubuntu/Debian)终端执行:
sudo a2enmod rewrite,再运行sudo systemctl restart apache2 - Windows 或手动编译 Apache:打开
httpd.conf,找到这行#LoadModule rewrite_module modules/mod_rewrite.so,删掉开头的#,保存后重启 Apache - 快速验证:新建一个 PHP 文件,写
<?php phpinfo(); ?>,浏览器打开后搜索 mod_rewrite,看到即表示已加载
允许 .htaccess 覆盖主配置
Apache 默认禁止目录级配置,需显式授权才能让 .htaccess 生效。
Apache Superset 是一个广泛采用的开源 BI 平台,用于 SQL 探索、图表构建和仪表板交付。当代理需要查询仓库数据、组装仪表板或使用成熟的分析界面解释指标而不是临时笔记本代码时,此技能非常有用。
- 编辑虚拟主机配置文件(如
/etc/apache2/sites-available/000-default.conf),在<virtualhost></virtualhost>内的<directory></directory>区块中添加或修改两行: AllowOverride All-
Require all granted(Apache 2.4+)或Order allow,deny && Allow from all(Apache 2.2) - 改完务必重启 Apache:
sudo systemctl restart apache2
编写博客常用重写规则
规则写在网站根目录的 .htaccess 文件里,开头必须加 RewriteEngine On。以下是几种典型博客场景:
-
文章页(ID 形式):
原始地址:/post.php?id=456→ 伪静态:/post/456/
规则:RewriteRule ^post/([0-9]+)/?$ post.php?id=$1 [L] -
文章页(年/月/别名):
原始地址:/article.php?year=2024&month=07&slug=hello-world→ 伪静态:/2024/07/hello-world.html
规则:RewriteRule ^([0-9]{4})/([0-9]{2})/([a-z0-9\-]+)\.html$ article.php?year=$1&month=$2&slug=$3 [L] -
分类归档页:
原始地址:/category.php?name=tech→ 伪静态:/category/tech/
规则:RewriteRule ^category/([a-z0-9\-]+)/?$ category.php?name=$1 [L] -
首页与通用兜底(可选):
避免访问不存在路径返回 500 错误,加一条防止无限循环:RewriteCond %{REQUEST_FILENAME} !-fRewriteCond %{REQUEST_FILENAME} !-dRewriteRule ^(.*)$ index.php?path=$1 [L,QSA](适合单入口框架型博客)
测试与调试要点
规则生效后,别忘了同步更新博客内部所有链接,否则用户点的还是旧地址。
- 浏览器访问伪静态 URL,检查页面是否正常加载,且地址栏显示的是新格式
- 查看 Apache 错误日志(
/var/log/apache2/error.log)排查 500 错误,常见原因是正则语法错、缺少[L]导致规则链冲突 - 用
RewriteLogLevel 3和RewriteLog "/path/to/rewrite.log"(仅 Apache 2.2)可详细追踪匹配过程;2.4+ 推荐用LogLevel alert rewrite:trace3配合ErrorLog - 注意特殊字符:点号
.要写成\.,斜杠不用转义,中文需确保服务器和文件编码为 UTF-8










