在部署 Web 应用时,Apache 的伪静态(URL Rewrite)功能至关重要。若遇到伪静态页面无法访问,通常是模块未加载、配置缺失或 .htaccess 规则错误所致。本文提供从编译安装到运行时配置的完整排查步骤。
源码编译 Apache 时,务必加入 --enable-rewrite 参数,使伪静态功能内建于核心:
./configure --prefix=/usr/local/apache2 --enable-so --enable-rewrite --enable-ssl
编译完成后,Apache 已具备原生伪静态能力。
若安装时遗漏 --enable-rewrite,可通过修改 httpd.conf 动态加载:
LoadModule 区域末尾LoadModule rewrite_module modules/mod_rewrite.so虚拟主机配置文件(通常在 /usr/local/apache2/conf/extra/httpd-vhosts.conf)中,将目标目录的 AllowOverride 由 None 改为 All:
Options FollowSymLinks
AllowOverride All
修改后重启 Apache。随后在网站根目录创建 .htaccess 并编写重写规则,例如:
RewriteEngine On
RewriteBase /
# 示例规则
RewriteRule ^index\.htm$ index.php
RewriteRule ^jobs/jobs-show-([0-9]+)\.htm$ jobs/jobs-show.php?id=$1
RewriteRule ^news/news-list-([0-9]+)-([0-9]+)\.htm$ news/news-list.php?id=$1&page=$2
# 其余规则同理...
若主站正常但子链接(如 .html 结尾)失效,多因 .htaccess 未生效或规则缺失。确保文件权限正确、Apache 已加载 mod_rewrite、虚拟主机配置允许覆盖,即可解决绝大多数伪静态访问问题。