php - 查询字符串隐藏

标签 php apache .htaccess

我想从网址中删除查询字符串。

For eg: localhost/index.php?page=value to localhost/index.php

我目前正在使用:

RewriteEngine On
RewriteCond %{REQUEST_URI} !^/index.php$
RewriteRule ^(.+)\.php$ /$1/? [R=301,L]
RewriteRule ^([A-Za-z0-9-]+)/?$ index.php?page=$1 [L]

这不是重写... 我做错了什么吗?

编辑

按照 Clive 的评论删除了 QSL

最佳答案

如果查询字符串不为空,我们将使用空查询字符串将原始请求重写为自身。

RewriteEngine On
RewriteCond %{QUERY_STRING} !^$
RewriteRule ^(.*)$ $1?

这已经包含在 Apache 中,但带有 [QSD] 查询字符串丢弃:

RewriteRule ^(.*)$ $1 [QSD]

注意:查询字符串允许您跟踪日志文件和外部源链接中的各种内容。这样做会限制这些选项。

这可能不是您想要做的(这样会丢失很多用于 SEO 的旧链接)。因此,以下是如何将旧查询字符串作为 301 重定向重定向到新 URL。对于不熟悉 RegEx 或 Apache 工作原理的人来说,这在视觉上会有点困惑。字符串第一部分以问号结尾表示“可能是前面的字符”。在本例中,我们在替换末尾附加了 ? (不是 REGEX 模式),因为 Apache 的默认行为类似于 [QSA] (查询字符串附加)根据Apache manual for the QSD flag 。因此,添加单个 ? 本身就是创建一个空查询字符串以使现有字符串无效。 StackOverflow 上有几个使用此方法的答案。

RewriteCond %{QUERY_STRING} page=(.*)
RewriteRule .* %1/? [R=301,L]

使用[QSD]你可以这样写:

RewriteCond %{QUERY_STRING} page=(.*)
RewriteRule .* %1/ [R=301,L,QSD]

您的其他匹配项采用 contact.php 之类的文件并将其重定向到 /contact/。这可能仍然有效。

RewriteCond %{REQUEST_URI} !^/index.php$
RewriteRule ^(.+)\.php$ /$1/? [R=301,L]

这条规则也可以用QSD来写:

RewriteRule ^(.+)\.php$ /$1/ [R=301,L,QSD]

关于php - 查询字符串隐藏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16883338/

相关文章:

php 内容类型

php - if 语句的奇怪行为 : always executing else block

php - javascript外部文件-调用函数失败

php - 当 url 中使用连字符 (-) 时,Htaccess 不起作用

java - 在网络浏览器中隐藏 href URL

php - apache 的奇怪 Memcached 问题

javascript - 未捕获的类型错误 : Cannot read property 'status' of undefined when running ajax php

apache - Mod Security - 正文请求长度太长?

android - Apache 2.4.6 - 发送 GZIP 内容有时会导致 "read more bytes of request body than expected"

apache - http-equiv ="X-UA-Compatible"content ="IE=edge,chrome=1"... 将其放入 .htaccess 中?