重定向时 .htaccess 中的 QUERY_STRING

发布于 2024-09-26 00:27:17 字数 668 浏览 1 评论 0原文

我如何允许访问者使用此链接 (www.example.com/news?id=34) 以便查看 (www.example.com/index.php?page=news&id=34)

现在我正在隐藏我的 PHP 文件的扩展名,以使链接看起来更好。当访问者访问 (www.example.com/news) 时,他们可以看到该页面 (www.example.com/index.php?page=news)。然而,当他们访问 (www.example.com/news?id=12) 时,他们会收到 404 错误。

此时,PHP 无法识别 id 参数。这是我的 .htaccess 文件中当前的内容

Options +FollowSymlinks
RewriteEngine on

# catch request with no querystring like /Home
RewriteCond %{QUERY_STRING} ^$
RewriteRule ^([^/]+)$ /index.php?page=$1 [L]

# make other requests with a non-empty query string go to /index.php?id=XXXXX
RewriteCond %{QUERY_STRING} ^.*$
RewriteRule ^$ /index.php?id=$1 [QSA,L]

How can I allow visitors to use this link (www.example.com/news?id=34) in order to see (www.example.com/index.php?page=news&id=34)

Right now I am hiding the extensions of my PHP files in order to make the links look nice. When visitors go to (www.example.com/news) they can see the page (www.example.com/index.php?page=news). However, when they go to (www.example.com/news?id=12) they get a 404 error.

At this point, PHP does not recognize the id parameter. Here is what I currently have in my .htaccess file

Options +FollowSymlinks
RewriteEngine on

# catch request with no querystring like /Home
RewriteCond %{QUERY_STRING} ^$
RewriteRule ^([^/]+)$ /index.php?page=$1 [L]

# make other requests with a non-empty query string go to /index.php?id=XXXXX
RewriteCond %{QUERY_STRING} ^.*$
RewriteRule ^$ /index.php?id=$1 [QSA,L]

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

ヤ经典坏疍 2024-10-03 00:27:17

您的第二个测试模式 (^$) 仅匹配用户未输入任何路径信息但包含查询字符串的情况(例如 www.example.com/?id =12)。另请注意,反向引用 $1 在该规则中也没有值。

最简单的解决方案是结合这两个规则,因为您可以使用 QSA 标志来为您完成附加 id=# 部分的工作:

Options +FollowSymlinks
RewriteEngine on

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^/]+)$ /index.php?page=$1 [QSA,L]

Your second test pattern (^$) only matches the case where the user doesn't put any path information in, but does include a query string (e.g. www.example.com/?id=12). Also note that the backreference $1 has no value in that rule either.

The simplest solution is to just combine the two rules, since you can use the QSA flag to do the work of appending the id=# part for you:

Options +FollowSymlinks
RewriteEngine on

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^/]+)$ /index.php?page=$1 [QSA,L]
灯下孤影 2024-10-03 00:27:17

由于查询不为空,第一条规则的条件失败。在没有该条件的情况下尝试,但使用以下条件:

RewriteCond $1 !=index.php
RewriteRule ^([^/]+)$ /index.php?page=$1 [L]

The condition of your first rule fails as the query is not empty. Try it without that condition but with the following condition instead:

RewriteCond $1 !=index.php
RewriteRule ^([^/]+)$ /index.php?page=$1 [L]
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文