简体   繁体   中英

Remove Trailing Slash from Specific URL using HTACCESS

How to force remove trailing slash from specific URL using 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

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:

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.

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/

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.

If however you do need a htaccess solution to remove the slash then the below should work for you.

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

This has been tested at http://htaccess.madewithlove.be/ and works for your example URLs.

if you mean an internal routine

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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