Home > Blockchain >  htaccess redirect using get parameters and remove same parameters
htaccess redirect using get parameters and remove same parameters

Time:08-31

Please help me need redirect search.html?searchword=value&searchphrase=all to search.html?searchword=value

I tried:

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

but it do not work.

CodePudding user response:

You may use it like this:

RewriteCond %{QUERY_STRING} (?:^|&)searchphrase= [NC]
RewriteCond %{QUERY_STRING} (?:^|&)(searchword=[^&]*) [NC]
RewriteRule ^search\.html$ %{REQUEST_URI}?%1 [R=301,L,NC,NE]

Changes are:

  • Order of RewriteCond is important. Keep the condition with capture group as last one
  • No need to repeat searchword again in target, just capture from RewriteCond and use it later as back-reference %1
  • Instead of using .* use [^&]* to match only value till you get next & or end of string
  • Match search.html in rule pattern to avoid matching anything else

CodePudding user response:

With your shown samples and attempts please try following .htaccess rules. Please make sure to clear your browser cache before testing your URLs.

RewriteEngine ON
RewriteCond %{THE_REQUEST} \s/(search\.html)\?(searchword=[^&]*)&searchphrase=all [NC]
RewriteRule ^ /%1?%2 [R=301,L,NE]
  • Related