在 CentOS 下配置 LAMP(Linux + Apache + MySQL + PHP)伪静态,核心就是 Apache 的 mod_rewrite 模块。下面按常见场景一步一步来。
httpd -M | grep rewrite
如果看到:
rewrite_module (shared)
说明已启用。
vim /etc/httpd/conf/httpd.conf
找到并取消注释:
LoadModule rewrite_module modules/mod_rewrite.so
通常有两种方式:
vim /etc/httpd/conf.d/你的站点.conf
示例:
<VirtualHost *:80>
ServerName www.example.com
DocumentRoot /var/www/html
<Directory "/var/www/html">
AllowOverride All
Require all granted
</Directory>
</VirtualHost>
⚠️ 关键点是:
AllowOverride All
vim /etc/httpd/conf/httpd.conf
找到:
<Directory "/var/www/html">
AllowOverride None
</Directory>
改为:
AllowOverride All
systemctl restart httpd
.htaccess 伪静态规则在网站根目录创建或编辑:
vim /var/www/html/.htaccess
RewriteEngine On
RewriteRule ^article/([0-9]+)$ index.php?id=$1 [L]
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php/$1 [QSA,PT,L]
RewriteCond %{HTTPS} !=on
RewriteRule ^(.*)$ https://%{HTTP_HOST}/$1 [L,R=301]
.htaccess 不生效确认:
AllowOverride All.htaccess 在网站根目录Require all granted
tail -f /var/log/httpd/error_log
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
<IfModule mod_rewrite.c>
Options +FollowSymlinks -Multiviews
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php/$1 [QSA,PT,L]
</IfModule>
1. 开启 mod_rewrite
2. 设置 AllowOverride All
3. 重启 httpd
4. 写 .htaccess
如果你用的是 CentOS 7 / 8、宝塔、LNMP,或者某个具体程序(WordPress / ThinkPHP / Laravel),可以告诉我,我给你精确配置方案。