如何使用 mod_rewrite 删除 URL 的一部分

发布于 2024-10-08 12:08:12 字数 568 浏览 0 评论 0原文

我试图从这里重定向

www.mysite.com/product.html?item=example

到:

www.mysite.com/example

我的 .htaccess 文件中有这个重写规则,但它不起作用:

RewriteRule ^/product\.html\?item=(.*)$ /$1 [R=301,L] 

非常感谢任何帮助。

这是我现在所拥有的:

RewriteCond %{QUERY_STRING} ^item=(.*)$
RewriteRule ^/product\.html$ /%1 [R=301,L] 

这是我删除规则开头的正斜杠并在规则末尾添加问号以删除查询字符串后的最终结果:

RewriteCond %{QUERY_STRING} ^item=(.*)$
RewriteRule ^product\.html$ /%1? [R=301,L] 

I am trying to redirect from this:

www.mysite.com/product.html?item=example

to:

www.mysite.com/example

I have this rewrite rule in my .htaccess file but it isn't working:

RewriteRule ^/product\.html\?item=(.*)$ /$1 [R=301,L] 

Any help is much appreciated.

Here's what I have now:

RewriteCond %{QUERY_STRING} ^item=(.*)$
RewriteRule ^/product\.html$ /%1 [R=301,L] 

And here is the Final result after I got rid of forward slash at the beginning of the rule and added a question mark at the end of the rule to get rid of the query string:

RewriteCond %{QUERY_STRING} ^item=(.*)$
RewriteRule ^product\.html$ /%1? [R=301,L] 

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

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

发布评论

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

评论(1

夏夜暖风 2024-10-15 12:08:12

因为您位于 .htaccess 文件中,所以您需要从 RewriteRule 中删除前导斜杠:

RewriteCond %{QUERY_STRING} ^item=(.*)$
RewriteRule ^product\.html$ /%1? [R=301,L]

在引用正在传递的查询字符串时,Apache 2.2 文档 mod_rewrite 是这样说的:

修改查询字符串

默认情况下,传递查询字符串
通过不变。但是,您可以
在替换字符串中创建 URL
包含查询字符串部分。简单地
在里面使用问号
替换字符串表明
以下文字应该是
重新注入到查询字符串中。
当您想要删除现有的
查询字符串,结束替换
仅带有问号的字符串。到
结合新旧查询字符串,使用
[QSA] 标志。

因此,正如您所发现的,您只需要在替换后添加 ? 即可。

Because you are in an .htaccess file, you'll want to remove the leading slash from your RewriteRule:

RewriteCond %{QUERY_STRING} ^item=(.*)$
RewriteRule ^product\.html$ /%1? [R=301,L]

In reference to the query string being passed through, the Apache 2.2 documentation for mod_rewrite says this about it:

Modifying the Query String

By default, the query string is passed
through unchanged. You can, however,
create URLs in the substitution string
containing a query string part. Simply
use a question mark inside the
substitution string to indicate that
the following text should be
re-injected into the query string.
When you want to erase an existing
query string, end the substitution
string with just a question mark. To
combine new and old query strings, use
the [QSA] flag.

So as you discovered, you need only to add a ? after the substitution.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文