linux apache下mod_rewrite伪静态规则需满足模块启用、allowoverride all配置及.htaccess正确放置;通用入口路由将非真实文件/目录请求交由index.php处理;业务规则按正则映射具体url格式;辅助规则可强制https、防盗链、自定义404等。

Linux Apache 下的 mod_rewrite 伪静态规则,核心是让动态 URL(如 /index.php?m=article&id=123)对外表现为静态形式(如 /article/123.html),既利于 SEO,又提升可读性和用户体验。实际生效需满足三个前提:模块已启用、AllowOverride All 已配置、.htaccess 文件位置和语法正确。
基础必备配置
所有规则运行前必须确保以下条件成立:
- mod_rewrite 模块已加载:执行
sudo a2enmod rewrite(Debian/Ubuntu)或确认httpd.conf中有LoadModule rewrite_module modules/mod_rewrite.so且未被注释 - 网站对应目录(如
<directory></directory>或虚拟主机段)中设置AllowOverride All,否则.htaccess将被忽略 -
.htaccess文件放在网站根目录,文件名严格为.htaccess(开头带点,不可写成htaccess或.htaccess.txt)
通用型入口路由规则(适用于多数 PHP 框架)
这类规则把所有非真实文件/目录的请求统一交由前端控制器(如 index.php)处理,是 Laravel、ThinkPHP、Typecho 等框架的标准写法:
<ifmodule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php [QSA,L]
</ifmodule>
说明:RewriteCond %{REQUEST_FILENAME} !-f 表示“请求路径不是真实存在的文件”;!-d 表示“不是真实存在的目录”;[QSA,L] 中 QSA 保留原始查询参数,L 表示终止后续规则匹配。
按需定制的常见业务规则
针对具体 URL 格式,用正则精准映射。注意顺序——靠前的规则优先匹配,建议把更具体的放前面:
- 将
/article/123.html→/index.php?m=article&id=123:RewriteRule ^article/([0-9]+)\.html$ /index.php?m=article&id=$1 [QSA,L] - 支持多级栏目,如
/news/tech/456.html→/index.php?c=news&s=tech&id=456:RewriteRule ^news/([^/]+)/([0-9]+)\.html$ /index.php?c=news&s=$1&id=$2 [QSA,L] - Discuz! 帖子页:
RewriteRule ^thread-([0-9]+)-([0-9]+)-([0-9]+)\.html$ /forum.php?mod=viewthread&tid=$1&extra=page%3D$2%26page%3D$3 [QSA,L] - PHPCMS 文章页:
RewriteRule ^show-([0-9]+)-([0-9]+)\.html$ /show.php?itemid=$1&page=$2 [QSA,L]
实用辅助规则(防坑 & 提效)
这些规则不直接改 URL 结构,但能解决常见问题:
- 强制 HTTPS(配合 SSL):
RewriteCond %{HTTPS} off<br>RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L] - 屏蔽图片盗链(保护带宽):
RewriteCond %{HTTP_REFERER} !^$<br>RewriteCond %{HTTP_REFERER} !^https?://(www\.)?yourdomain\.com/ [NC]<br>RewriteRule \.(jpg|jpeg|png|gif|webp)$ - [F] - 自定义 404 页面(当请求路径不存在时):
RewriteCond %{REQUEST_FILENAME} !-f<br>RewriteCond %{REQUEST_FILENAME} !-d<br>RewriteRule .? /404.php [L] - 移除 URL 中的 www(或反之):
RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]<br>RewriteRule ^(.*)$ https://%1/$1 [R=301,L]
每条规则上线前建议用在线正则测试工具验证表达式,Apache 配置修改后务必重启服务(sudo systemctl restart apache2);遇到 500 错误可先检查 .htaccess 语法,并临时启用 Apache 的 RewriteLog(仅调试用)定位问题。











