在 CentOS 下给 Apache 开启伪静态(URL Rewrite),一般按下面几步来即可(以 CentOS 7 + Apache 2.4 为例,绝大部分都适用)。
httpd -v
或
apachectl -v
CentOS 下 Apache 默认未启用 rewrite 模块。
httpd -M | grep rewrite
如果没有任何输出,说明未开启。
编辑 Apache 配置文件:
vi /etc/httpd/conf/httpd.conf
找到下面这行(一般在靠前位置):
#LoadModule rewrite_module modules/mod_rewrite.so
去掉前面的 #
LoadModule rewrite_module modules/mod_rewrite.so
伪静态通常依赖 .htaccess。
常见位置:
vi /etc/httpd/conf/httpd.conf
或
vi /etc/httpd/conf.d/*.conf
<Directory> 配置例如你的网站目录是 /var/www/html:
<Directory "/var/www/html">
AllowOverride All
Require all granted
</Directory>
⚠️ AllowOverride None 必须改成 All,否则伪静态无效。
systemctl restart httpd
在网站根目录创建 .htaccess:
RewriteEngine On
RewriteRule ^test$ index.php [L]
访问:
http://你的IP/test
如果能访问说明 rewrite 已生效 ✅
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php/$1 [QSA,PT,L]
</IfModule>
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
| 问题 | 解决方法 |
|---|---|
| 页面 404 | 检查 AllowOverride |
| 规则不生效 | 确认 mod_rewrite 已加载 |
| 改了配置没反应 | 重启 Apache |
| 服务器是宝塔 | 直接在 网站 → 伪静态 里选 |
如果你用的是 宝塔 / LNMP / 某个具体 CMS,可以告诉我,我可以直接给你对应配置。