在Apache2中配置伪静态规则通常涉及修改或创建一个.htaccess
文件,或者直接在虚拟主机配置文件中添加规则。以下是一些基本的步骤和示例,帮助你开始配置伪静态规则。
.htaccess
文件找到或创建 .htaccess
文件:
/var/www/html/your-site
)。编辑 .htaccess
文件:
.htaccess
文件进行编辑。添加伪静态规则:
RewriteEngine On
# 将 /article/123 重写为 /article.php?id=123
RewriteRule ^article/([0-9]+)$ article.php?id=$1 [L]
# 将 /category/news 重写为 /category.php?cat=news
RewriteRule ^category/([a-zA-Z]+)$ category.php?cat=$1 [L]
# 将 /user/john 重写为 /user.php?username=john
RewriteRule ^user/([a-zA-Z0-9]+)$ user.php?username=$1 [L]
如果你更喜欢直接在Apache的虚拟主机配置文件中添加规则,可以按照以下步骤操作:
找到虚拟主机配置文件:
/etc/apache2/sites-available/
目录下。编辑虚拟主机配置文件:
添加伪静态规则:
<Directory>
或 <Location>
块中添加 RewriteRule
。<VirtualHost *:80>
ServerAdmin webmaster@localhost
DocumentRoot /var/www/html/your-site
<Directory /var/www/html/your-site>
Options Indexes FollowSymLinks
AllowOverride All
Require all granted
</Directory>
RewriteEngine On
# 将 /article/123 重写为 /article.php?id=123
RewriteRule ^article/([0-9]+)$ article.php?id=$1 [L]
# 将 /category/news 重写为 /category.php?cat=news
RewriteRule ^category/([a-zA-Z]+)$ category.php?cat=$1 [L]
# 将 /user/john 重写为 /user.php?username=john
RewriteRule ^user/([a-zA-Z0-9]+)$ user.php?username=$1 [L]
</VirtualHost>
无论你是在 .htaccess
文件中添加规则还是在虚拟主机配置文件中添加规则,都需要重启Apache服务器以使更改生效。
sudo systemctl restart apache2
AllowOverride
设置为 All
或至少包含 FileInfo
,以便 .htaccess
文件中的规则能够生效。[L]
标志表示这是最后一条规则,如果匹配则停止进一步处理。[NC]
标志表示不区分大小写(例如 RewriteRule ^article/([a-z]+)$ article.php?id=$1 [NC,L]
)。通过以上步骤,你应该能够在Apache2中成功配置伪静态规则。