在 CentOS 上,使用 Apache 配置“伪静态”(URL Rewrite)通常是通过 mod_rewrite 模块实现的。下面按常见场景一步步说明。
httpd -v
# 或
apachectl -v
httpd -M | grep rewrite
如果有:
rewrite_module (shared)
说明已启用。
如果没有,编辑 Apache 配置:
vi /etc/httpd/conf/httpd.conf
找到并取消注释(删掉前面的 #):
LoadModule rewrite_module modules/mod_rewrite.so
Apache 默认可能禁止 .htaccess 重写规则生效。
编辑虚拟主机或主配置:
vi /etc/httpd/conf/httpd.conf
或
vi /etc/httpd/conf.d/your-site.conf
示例:
<Directory "/var/www/html">
AllowOverride All
Require all granted
</Directory>
⚠️ 如果是 CentOS 7+,默认是 Apache 2.4,用
Require all granted
重启 Apache:
systemctl restart httpd
进入网站根目录:
cd /var/www/html
vi .htaccess
RewriteEngine On
index.php?id=1 伪静态成 /article/1RewriteEngine On
RewriteRule ^article/([0-9]+)$ index.php?id=$1 [L]
访问:
http://域名/article/1
实际执行:
index.php?id=1
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php/$1 [QSA,PT,L]
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
也可以不写 .htaccess,直接写在 <VirtualHost> 中:
<VirtualHost *:80>
DocumentRoot /var/www/html
ServerName example.com
<Directory /var/www/html>
AllowOverride All
Require all granted
</Directory>
RewriteEngine On
RewriteRule ^article/([0-9]+)$ index.php?id=$1 [L]
</VirtualHost>
.htaccess 是否在网站根目录AllowOverride All 是否配置Require all granted
在 httpd.conf 中加:
LogLevel alert rewrite:trace3
然后:
tail -f /var/log/httpd/error_log
如果你用的是 CentOS + 宝塔 / LNMP / 某个框架(ThinkPHP、Laravel、WordPress),可以告诉我,我可以给你更精确的配置。