在 CentOS 系统中,Apache2 通常被称为 httpd
- 首先确保已经安装了 Apache 服务器。如果没有,请使用以下命令安装:
sudo yum install httpd
- 启动 Apache 服务并设置开机启动:
sudo systemctl start httpd sudo systemctl enable httpd
- 使用文本编辑器(如 vim)打开 Apache 配置文件。通常,配置文件位于
/etc/httpd/conf/httpd.conf
:
sudo vim /etc/httpd/conf/httpd.conf
- 在配置文件中找到
部分,允许.htaccess
文件覆盖配置。如果没有这个部分,请添加以下内容:
AllowOverride All
这里,/var/www/html
是你的网站根目录,可以根据实际情况进行修改。
-
保存并关闭配置文件。
-
在网站根目录下创建或编辑
.htaccess
文件。例如,如果网站根目录是/var/www/html
,则使用以下命令创建或编辑.htaccess
文件:
sudo vim /var/www/html/.htaccess
- 在
.htaccess
文件中编写 URL 重写规则。以下是一些常见的示例:
- 将带有扩展名的 URL 重写为不带扩展名的 URL:
RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME}\.html -f RewriteRule ^(.*)$ $1.html
- 将 URL 重写到另一个目录:
RewriteEngine On RewriteRule ^old-page$ /new-page [R=301,L]
- 将带有查询参数的 URL 重写为更友好的 URL:
RewriteEngine On RewriteCond %{QUERY_STRING} ^id=(\d+)$ RewriteRule ^product$ /product.php?id=%1 [R=301,L]
-
保存并关闭
.htaccess
文件。 -
重新启动 Apache 服务以使更改生效:
sudo systemctl restart httpd
现在,你的 CentOS 系统上的 Apache2 服务器已经配置好了 URL 重写规则。请根据实际需求调整示例中的规则。