在 CentOS 上让 PHP 支持“重写”,通常是 Apache 的 mod_rewrite 或 Nginx 的 rewrite,而不是 PHP 本身。下面分别说明。
httpd -M | grep rewrite
看到 rewrite_module 说明已启用。
若没有:
yum install mod_rewrite
systemctl restart httpd
编辑配置文件(以虚拟主机为例):
vi /etc/httpd/conf/httpd.conf
或
vi /etc/httpd/conf.d/xxx.conf
确保:
<Directory "/var/www/html">
AllowOverride All
</Directory>
⚠️
AllowOverride None会导致.htaccess不生效
systemctl restart httpd
RewriteEngine On
RewriteRule ^test$ index.php?id=test [L]
Nginx 没有 .htaccess,在 server 块中配置:
server {
listen 80;
server_name example.com;
root /usr/share/nginx/html;
location / {
try_files $uri $uri/ /index.php?$query_string;
}
location ~ \.php$ {
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
include fastcgi.conf;
}
}
重启:
systemctl restart nginx
PHP 只是接收重写后的请求,例如:
/index.php?id=123
AllowOverride 没设对.htaccess 语法错误如果你能告诉我:
我可以给你精准配置示例。