简体   繁体   English

使用HTACCESS从特定URL删除尾部斜杠

[英]Remove Trailing Slash from Specific URL using HTACCESS

How to force remove trailing slash from specific URL using htaccess, 如何使用htaccess强制从特定网址中删除尾部斜杠,

For example : 例如 :

https://blahblah.com/checkout/?checkout=add_to_cart&id=17&item_options[price_id]=1/

to

https://blahblah.com/checkout/?checkout=add_to_cart&id=17&item_options[price_id]=1

and ignore other URL such as https://blahblah.com/about/ or https://blahblah.com/contact/ etc 并忽略其他网址,例如https://blahblah.com/about/https://blahblah.com/contact/

Because the trailing slash is part of the querystring you can't just rewrite it, you have to extract the querystring minus that final / and then redirect to the page you're on with that match appended. 因为尾部的斜杠是查询字符串的一部分,所以您不能只重写它,因此必须提取减去最后一个/的查询字符串,然后重定向到附加了该匹配项的页面。

To do this you need to match on the pattern in the RewriteCond with %1 (see this answer for reference) and append that to the %{REQUEST_URI} (thus removing the original querystring) - like this: 为此,您需要将RewriteCond中的模式与%1匹配(请参阅此答案以供参考),并将其附加到%{REQUEST_URI} (从而删除原始查询字符串)中,如下所示:

RewriteEngine On
RewriteCond %{QUERY_STRING} ^(.*)/$
RewriteRule ^.*$ %{REQUEST_URI}?%1 [L,R=301]

RewriteCond %{QUERY_STRING} ^(.*)/$ <-- make sure you've got that / at the end here in your conditional - it ensures that only querystrings that end with / are redirected so you don't end up in a horrible recursive loop. RewriteCond %{QUERY_STRING} ^(.*)/$ < -确保你已经得到了/在这里到底在你的条件-它确保只有结尾查询字符串/重定向,所以你不结束一个可怕的递归循环。

You can try this: 您可以尝试以下方法:

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

This will redirect every request containing query strings only. 这将重定向每个仅包含查询字符串的请求。 In your case this: 就您而言:

checkout/?checkout=add_to_cart&id=17&item_options[price_id]=1/

to

checkout/?checkout=add_to_cart&id=17&item_options[price_id]=1

But not this https://blahblah.com/about/ and https://blahblah.com/contact/ 但是不是这个https://blahblah.com/about/https://blahblah.com/contact/

I would advise trying to find out why that trailing slash is there to begin with first. 我建议尝试先找出为什么在后面加上斜杠。 As CD001 said in the comments it could be that your PHP code is doing something wrong. 正如CD001在评论中所说,这可能是您的PHP代码做错了什么。

If however you do need a htaccess solution to remove the slash then the below should work for you. 但是,如果您确实需要htaccess解决方案来删除斜杠,那么以下内容将为您工作。

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

This has been tested at http://htaccess.madewithlove.be/ and works for your example URLs. 这已经在http://htaccess.madewithlove.be/上进行了测试,适用于您的示例URL。

if you mean an internal routine 如果您的意思是内部例程

RewriteCond %{QUERY_STRING} ^(checkout\=[^\&\s]+\&id\=\d+\&item_options\[price_id\]\=\d+)\/
RewriteRule ^ %{REQUEST_FILENAME}?%1 [L]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM