在 Apache 中开启“伪静态”(URL Rewrite),通常是指使用 mod_rewrite 模块,把动态 URL(如 index.php?id=1)伪装成静态 URL(如 /article/1.html)。下面按常见场景一步步说明。
apache2ctl -M | grep rewrite
或
httpd -M | grep rewrite
如果看到:
rewrite_module (shared)
说明已启用 ✅
sudo a2enmod rewrite
sudo systemctl restart apache2
vi /etc/httpd/conf/httpd.conf
确保有:
LoadModule rewrite_module modules/mod_rewrite.so
然后重启:
systemctl restart httpd
Apache 默认可能不允许 .htaccess 覆盖规则。
<Directory "/var/www/html">
AllowOverride All
Require all granted
</Directory>
⚠ 如果是 Ubuntu,通常在:
/etc/apache2/sites-enabled/000-default.conf
修改后重启 Apache:
sudo systemctl restart apache2
.htaccessvi /var/www/html/.htaccess
RewriteEngine On
# 将 /article/1 转发给 index.php
RewriteRule ^article/([0-9]+)$ index.php?id=$1 [L,QSA]
访问:
http://example.com/article/1
实际执行:
index.php?id=1
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php/$1 [QSA,L]
RewriteRule ^news-([0-9]+)\.html$ news.php?id=$1 [L]
访问:
/news-123.html
RewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteRule ^(.*)$ https://%{HTTP_HOST}/$1 [R=301,L]
✅ 检查:
AllowOverride All.htaccess 是否在正确目录✅ 检查:
RewriteRule 语法错误查看错误日志:
tail -f /var/log/apache2/error.log
1. 启用 mod_rewrite
2. 设置 AllowOverride All
3. 重启 Apache
4. 编写 .htaccess
如果你用的是 宝塔 / LNMP / 某个 CMS(WordPress、ThinkPHP、帝国、织梦),可以告诉我具体环境,我可以给你 专用伪静态规则 ✅