温馨提示×

centos php如何开启重写

小樊
48
2026-09-24 02:23:08
栏目: 编程语言

在 CentOS 上让 PHP 支持“重写”,通常是 Apache 的 mod_rewrite 或 Nginx 的 rewrite,而不是 PHP 本身。下面分别说明。


一、Apache(最常见,CentOS 默认)

1. 确认 mod_rewrite 已安装并启用

httpd -M | grep rewrite

看到 rewrite_module 说明已启用。

若没有:

yum install mod_rewrite
systemctl restart httpd

2. 修改 Apache 配置(关键)

编辑配置文件(以虚拟主机为例):

vi /etc/httpd/conf/httpd.conf

或

vi /etc/httpd/conf.d/xxx.conf

确保:

<Directory "/var/www/html">
    AllowOverride All
</Directory>

⚠️ AllowOverride None 会导致 .htaccess 不生效


3. 重启 Apache

systemctl restart httpd

4. 使用 .htaccess 示例

RewriteEngine On
RewriteRule ^test$ index.php?id=test [L]

二、Nginx(CentOS + PHP-FPM)

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 本身不需要“开启重写”

PHP 只是接收重写后的请求,例如:

/index.php?id=123

四、常见问题排查

  • 404 → AllowOverride 没设对
  • 500 → .htaccess 语法错误
  • 重写无效 → 没重启服务

如果你能告诉我:

  • ✅ CentOS 版本(7 / 8 / Stream)
  • ✅ Apache 还是 Nginx
  • ✅ 用的是框架(ThinkPHP / Laravel / 原生)

我可以给你精准配置示例。

0 踩