Search code examples
.htaccess

Restrict URL Paramater by htaccess rule


I'm trying to restrict parameter by htaccess below are the example which i want to achieve

This parameter is valid & htaccess rule will be allowing it

example.com/test?param=somevalue 

This parameter should be restrict OR change parameter name by htaccess

Parameter Sample URL

example.com/test?param[]=somevalue 

Redirect to

example.com/test?param=somevalue 

OR

example.com/test

I tried some rules of htaccess and restricting parameter without these bracket

[]

but i'm not able to restrict parameters which containing [] in name.


Solution

  • You can catch the brackets by escaping them in the condition:

    RewriteCond %{QUERY_STRING} (?:^|&)(foo)(?:\[\])?=(.*)(?:&|$)
    RewriteRule ^ %{REQUEST_URI}?%1=%2
    

    This rewrites https://example.com/test?foo[]=bar to https://example.com/test?foo=bar.

    Note however that there is a sematic meaning for parameters with a trailing "[]" for php applications (and maybe others): those parameters are provided as arrays to the requested resource. And they potentially occur multiple times in a request's query string, which is why they are names in such manner. So take care that you don't break the application logic by this parameter modification.