Rafael Degelo
Rafael Degelo

Reputation: 9

How do I remove a query string from my URL?

I'm looking to remove a query string from my URL like below:

The URL currently looks like this:

http://example.com/?s=cadeira&dgwt-wcas-search-submit=&post_type=product&dgwt_wcas=1

What I want:

http://example.com/?s=cadeira

I'm not very good with .htaccess, anyone can help me with that?

Upvotes: 0

Views: 415

Answers (2)

MrWhite
MrWhite

Reputation: 45829

remove a query string at my url?

The "query string" is everything after the ? in the URL. What you are referring to is a single URL parameter inside the query string.

In order to keep just the s URL parameter in the query string and remove everything else, you can do something like the following at the top of the root .htaccess file:

RewriteCond %{QUERY_STRING} (?:^|&)(s=[^&]+)
RewriteRule ^$ /?%1 [R=302,L]

This only matches requests for the document root (ie. an empty URl-path). If the s URL parameter does not occur in the query string then nothing happens. The %1 backreference matches the s=<value> part from the query string. Everything else in the query string is discarded.

Note that this will match the s= URL parameter anywhere in the query string. In your example this appears at the start of the query string. If you specifically only want to match s= when it appears at the start of the query string then change the CondPattern to read: ^(s=[^&]+). ie. RewriteCond %{QUERY_STRING} ^(s=[^&]+).

A 302 (temporary) redirect is issued to actually remove the other URL parameters from the query string.

Upvotes: 1

Ahmed Eid
Ahmed Eid

Reputation: 144

you can split the string at the first & in the URL

$pos = strpos($url, "&");
$url = substr($url, 0, $pos);

Upvotes: 0

Related Questions