.htaccess 重写规则的问题

问题描述 投票:0回答:1

我今天玩了一下 .htaccess,因为我想尝试创建平面链接。我的代码:

RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

RewriteRule ^$ router.php?path=home [L]

RewriteRule ^([^/]+)/?$ router.php?path=$1 [L,QSA]

RewriteRule ^([^/]+)/([^/]+)/?$ router.php?path=$1&target=$2 [L,QSA]

我现在的两个问题是,第一条规则不适用于 example.com/,我只得到一个禁止错误,并且规则不会将链接 https://example.com/home 更改为 https: //example.com/router.php?path=home 但 QUERY_STRING 是“path=router&path=home”。我在 router.php 中所做的就是打印 $_SERVER["QUERY_STRING"]....

查看了apache2.conf,根据几个教程其设置正确,尝试了chatgpt,失败,尝试添加+SymLinksIfOwnerMatched,没有做任何事情...

有人可以帮我吗?

提前致谢!

.htaccess webserver apache2
1个回答
0
投票

您似乎正在尝试在 .htaccess 文件中使用 mod_rewrite 来创建干净且用户友好的 URL。但是,您遇到了一些问题。让我们一一解决:

1。根 URL 禁止错误:

根 URL (example.com/) 的禁止错误可能是由于 Apache 的默认目录列表设置造成的。当你将 URL 重写为空路径时,Apache 可能不知道如何处理。要解决此问题,您可以显式指定根 URL 的目标,如下所示:

RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

RewriteRule ^$ router.php?path=home [L]

RewriteRule ^([^/]+)/?$ router.php?path=$1 [L,QSA]

RewriteRule ^([^/]+)/([^/]+)/?$ router.php?path=$1&target=$2 [L,QSA]

通过添加第一个 RewriteRule,您可以确保即使是根 URL 也会使用

router.php
参数重定向到
path=home

2。查询字符串问题:

查询字符串 (

path=router&path=home
) 的问题是由于 RewriteRules 中的
[QSA]
标志造成的。该标志将原始查询字符串附加到重写的 URL 中。要解决此问题并仅保留
path
参数,您可以像这样修改规则:

RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

RewriteRule ^$ router.php?path=home [L]

RewriteRule ^([^/]+)/?$ router.php?path=$1 [L]

RewriteRule ^([^/]+)/([^/]+)/?$ router.php?path=$1&target=$2 [L]

这应该确保您重写的 URL 中只有一个

path
参数。

进行这些更改后,不要忘记重新启动 Apache 以应用新的

.htaccess
规则。

此外,请确保在您的 Apache 配置中启用

mod_rewrite
,并且您的
.htaccess
文件位于您网站的根目录中并且正在被 Apache 读取。

© www.soinside.com 2019 - 2024. All rights reserved.