Home > Blockchain >  RewriteRule to capture whole search string produces empty result
RewriteRule to capture whole search string produces empty result

Time:07-29

I have the following rule in .htaccess:

RewriteRule ^order(.*)$ /index.php?p=order&product=$1 [L,NC]

It's a simplification because later on I want to add order\?product=(.*)

I access the website with:

http://website.com/order?product=L0231-03868 but in the $_GET I'm only getting this:

Array ( [p] => skonfiguruj-zamowienie [product] => )

The product is empty. What am I missing?

-- edit the moment I add the question mark

RewriteRule ^order\?(.*)$ /index.php?p=order&product=$1 [L,NC]

I get 404

CodePudding user response:

With your shown samples please try following htacces rules file. Make sure to keep your htaccess rules file along with index.php file, order folder(3 of them should reside inside root directory). Also clear cache before testing your URLs.

RewriteEngine ON
RewriteCond %{THE_REQUEST} \s/(order)\?(product)=(\S )\s [NC]
RewriteRule ^  index.php?p=%1&%2=%3 [QSA,L]

To make it more Generic, as above rules are very samples specific only:

RewriteEngine ON
RewriteCond %{THE_REQUEST} \s/([^?]*)\?([^=]*)=(\S )\s [NC]
RewriteRule ^  index.php?p=%1&%2=%3 [QSA,L]

Documentation link:

%{THE_REQUEST} is being used here, which contains complete request line.

CodePudding user response:

  • Your URI doesn't really have anything after order so there is nothing to capture in (.*).
  • Use QSA flag to append original query string after rewrite.
  • No need to repeat order on both sides.

Suggested rule:

RewriteRule ^(order)/?$ index.php?p=$1 [L,NC,QSA]

Because of QSA flag, your original query string product=L0231-03868 will be appended to p=order and you will get both parameters in php file.


Note about patter ^order\?(.*)$ generating 404. Remember that a ? will never be part of URI to be matched using RewriteRule hence this pattern containing a ? is guaranteed to always fail.

  • Related