在 CentOS 上让 Apache 支持 伪静态(URL Rewrite),通常是通过 mod_rewrite 模块实现的。下面按常见场景一步步说明。
httpd -v
或
apachectl -v
如果未安装:
yum install -y httpd
systemctl start httpd
systemctl enable httpd
httpd -M | grep rewrite
如果看到:
rewrite_module (shared)
说明已启用 ✅
编辑 Apache 配置文件:
vi /etc/httpd/conf/httpd.conf
确认或添加:
LoadModule rewrite_module modules/mod_rewrite.so
Apache 默认可能禁止 .htaccess 生效,需要修改 AllowOverride
vi /etc/httpd/conf/httpd.conf
找到类似:
<Directory "/var/www/html">
AllowOverride None
</Directory>
改为:
<Directory "/var/www/html">
AllowOverride All
</Directory>
✅ AllowOverride All 是伪静态生效的关键
systemctl restart httpd
进入网站根目录(如 /var/www/html):
cd /var/www/html
vi .htaccess
RewriteEngine On
RewriteRule ^article/([0-9]+)\.html$ article.php?id=$1 [L]
访问:
http://yourdomain/article/123.html
实际执行:
article.php?id=123
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
✅ 检查:
AllowOverride All 是否设置cat /etc/httpd/conf/httpd.conf | grep AllowOverride
确认不是:
AllowOverride None
chmod 755 .htaccess
如果仍不生效,可能是 SELinux 限制:
setenforce 0
setsebool -P httpd_can_network_connect 1
mod_rewriteAllowOverride All.htaccess如果你用的是 CentOS 7 / 8 / Stream、宝塔面板、WordPress / Laravel / ThinkPHP,可以告诉我,我可以给你更精确的配置示例。