在 CentOS + Apache 环境下做“伪静态”,通常是通过 mod_rewrite 模块和 .htaccess(或虚拟主机配置)来实现。下面按常见场景给你说明。
httpd -M | grep rewrite
如果看到:
rewrite_module (shared)
说明已启用。
如果没有,启用它:
sudo yum install mod_rewrite
sudo systemctl restart httpd
Apache 默认可能不允许目录使用 .htaccess,需要修改配置。
编辑站点配置(例如):
sudo vi /etc/httpd/conf.d/your-site.conf
确保有如下内容:
<Directory "/var/www/html">
AllowOverride All
</Directory>
sudo systemctl restart httpd
在网站根目录创建或编辑 .htaccess:
RewriteEngine On
# 例子:将 /article/123.html 转发到 index.php?a=123
RewriteRule ^article/([0-9]+)\.html$ index.php?a=$1 [L]
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L]
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php [L]
比 .htaccess 性能更好:
<VirtualHost *:80>
ServerName example.com
DocumentRoot /var/www/html
<Directory "/var/www/html">
AllowOverride All
Require all granted
</Directory>
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php [L]
</VirtualHost>
AllowOverride All.htaccess 是否在正确目录tail -f /var/log/httpd/error_log
.htaccess:
RewriteEngine On
RewriteRule ^test/([0-9]+)$ test.php?id=$1 [L]
访问:
/test/5
实际执行:
/test.php?id=5
如果你用的是 ThinkPHP / WordPress / Laravel / Discuz 等具体程序,可以告诉我,我可以直接给你对应伪静态规则。