在 CentOS 上配置 PHP 的 URL 重写规则,通常需要使用 Apache 或 Nginx 作为 Web 服务器。以下是针对这两种服务器的详细步骤:
安装 Apache 和 mod_rewrite 模块:
sudo yum install httpd
sudo systemctl start httpd
sudo systemctl enable httpd
启用 mod_rewrite 模块:
sudo systemctl enable httpd-mod_rewrite
sudo systemctl restart httpd
编辑 Apache 配置文件:
打开 Apache 的主配置文件 /etc/httpd/conf/httpd.conf 或者虚拟主机配置文件(通常位于 /etc/httpd/conf.d/ 目录下),添加或修改以下内容:
<Directory "/var/www/html">
AllowOverride All
</Directory>
创建或编辑 .htaccess 文件:
在你的网站根目录(例如 /var/www/html)下创建或编辑 .htaccess 文件,添加 URL 重写规则。例如:
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
这个规则会将所有非文件和非目录的请求重写到 index.php。
安装 Nginx:
sudo yum install epel-release
sudo yum install nginx
sudo systemctl start nginx
sudo systemctl enable nginx
编辑 Nginx 配置文件:
打开 Nginx 的主配置文件 /etc/nginx/nginx.conf 或者虚拟主机配置文件(通常位于 /etc/nginx/conf.d/ 或 /etc/nginx/sites-available/ 目录下),添加或修改以下内容:
server {
listen 80;
server_name example.com; # 替换为你的域名
root /var/www/html; # 替换为你的网站根目录
index index.php index.html index.htm;
location / {
try_files $uri $uri/ /index.php?$query_string;
}
location ~ \.php$ {
include snippets/fastcgi-php.conf;
fastcgi_pass unix:/var/run/php-fpm/php-fpm.sock; # 确保 PHP-FPM 正在运行
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
}
重启 Nginx:
sudo systemctl restart nginx
无论使用哪种服务器,都可以通过访问你的网站来验证 URL 重写规则是否生效。例如,如果你有一个规则将所有请求重写到 index.php,那么访问任何非文件和非目录的 URL 都应该返回 index.php 的内容。
希望这些步骤能帮助你在 CentOS 上成功配置 PHP 的 URL 重写规则!