Sthita
Sthita

Reputation: 1782

Checking if query_string has a value or else redirect it

I am learning .htaccess
My URL string is

http://abc.bcd.com/company/abc

I do apply to redirect my page if the company name is abc, xyz etc. and my rewrite rule is

RewriteRule ^/company/(.*?)$ /hhhhh/ll/test_page.html?company_letter=$1    [L,PT]

Sometimes my url change to

http://abc.bcd.com/company/abc?locale=en

What will be query string condition to accommodate both the url and should work properly ?

I have tried this but not helping .

RewriteCond %{QUERY_STRING} ^locale=(.*)$

The rewrite condition should help me like

if(locale="something")
  /hhhhh/ll/test_page.html?company_letter=abc&locale=something
else
  /hhhhh/ll/test_page.html?company_letter=abc

Upvotes: 2

Views: 2015

Answers (2)

anubhava
anubhava

Reputation: 785196

You just need to add QSA flag in your rule:

RewriteRule ^/?company/(.*)$ /hhhhh/ll/test_page.html?company_letter=$1 [L,QSA]

QSA (Query String Append) flag preserves existing query parameters while adding a new one.

Upvotes: 1

regilero
regilero

Reputation: 30496

The query string part of the incoming URL is a very specific thing. First you should know that classical rewriteRules are not managing the query string.

So, for example, you cannot make a RewriteRule with a check for a query string parameter value. Query strings parameters could be repeted several times, could appear in any order, and are not url-decoded (the location part of the url is url-decoded when mod_rewrite works on it).

This explains why some RewriteCond are sometimes used on the %{QUERY_STRING}, it cannot be done in RewriteRule but could be tested in rewriteCond, with all the previous probelsm ( repetition, order, url-encoding, etc).

But some rewriteRule tags can be applied for query string managment. Currently your tags are [L,PT], which also be writtent [last,passthrough].
You can add a qsappend or QSA tag which explicitly tells mod_rewrite to combine the original query string and the generated one.

So with

RewriteRule ^/company/(.*?)$ /hhhhh/ll/test_page.html?company_letter=$1    [last,passthrough,qsappend]

This:

http://abc.bcd.com/company/abc

Will go to

/hhhhh/ll/test_page.html?company_letter=abc

And this:

http://abc.bcd.com/company/abc?locale=en

Will go to

/hhhhh/ll/test_page.html?company_letter=abc&locale=en

Upvotes: 1

Related Questions