在 CentOS 上设置 Apache 伪静态(URL Rewrite),通常是指使用 mod_rewrite 模块来实现。下面按常见场景一步步说明。
httpd -v
# 或
apachectl -v
如果没有安装:
yum install httpd -y
systemctl start httpd
systemctl enable httpd
httpd -M | grep rewrite
如果看到:
rewrite_module (shared)
说明已启用。
✅ CentOS 7/8 默认已启用 mod_rewrite
如果没有,可手动加载(一般不用):
vim /etc/httpd/conf/httpd.conf
确认有:
LoadModule rewrite_module modules/mod_rewrite.so
Apache 默认可能不允许使用 .htaccess。
vim /etc/httpd/conf/httpd.conf
找到你的网站目录配置(如 /var/www/html):
<Directory "/var/www/html">
AllowOverride None
</Directory>
✅ 修改为:
<Directory "/var/www/html">
AllowOverride All
</Directory>
⚠️ AllowOverride None → All 是伪静态生效的关键
systemctl restart httpd
进入网站根目录:
cd /var/www/html
创建或编辑 .htaccess:
vim .htaccess
RewriteEngine On
# 将 index.php?id=1 转为 /1.html
RewriteRule ^([0-9]+)\.html$ index.php?id=$1 [L]
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php/$1 [QSA,L]
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
如果配置正确但仍 404,可能是 SELinux 限制。
setenforce 0
vim /etc/selinux/config
SELINUX=disabled
允许 Apache 使用伪静态:
setsebool -P httpd_can_network_connect 1
setsebool -P httpd_enable_homedirs 1
访问:
http://服务器IP/1.html
如果正确跳转到:
index.php?id=1
✅ 伪静态成功
| 问题 | 解决方案 |
|---|---|
| 404 | 检查 AllowOverride All |
| 500 | .htaccess 语法错误 |
| 规则不生效 | 确认 mod_rewrite 已加载 |
| 修改无效 | 重启 httpd |
yum install httpd -y
systemctl start httpd
vim /etc/httpd/conf/httpd.conf
# AllowOverride None → All
systemctl restart httpd
然后创建 .htaccess 并写 RewriteRule 即可 ✅
如果你用的是 CentOS 7 / 8 / 9、宝塔面板、ThinkPHP / Laravel / WordPress,可以告诉我,我可以给你对应环境的精确配置。