.htaccess - PHP - URL with multiple parameters and same name causing unexpected behaviour ← (PHP, HTML)

Solution:

PHP recognizes brackets [] appended to a parameter, e.g.

http://localhost/settings/account/?path[]=profile&path[]=account&path[]=profile

will be translated into an array

$path = $_GET['path'];
print_r($path);

shows

Array ( [0] => profile [1] => account [2] => profile )

This way, you can access any of the "paths" you like.


I could imagine some surgery, in order to remove part of a query string

RewriteCond %{QUERY_STRING} ^(.*)&path=.*?&(.*)$
RewriteRule ^ %{REQUEST_URI}?%1&%2

RewriteCond %{QUERY_STRING} ^path=.*?&(.*)$
RewriteRule ^ %{REQUEST_URI}?%1

RewriteCond %{QUERY_STRING} ^(.*)&path=.*$
RewriteRule ^ %{REQUEST_URI}?%1

Depending on where the path is, this would remove it from the query string. And finally, the last rule would add the new path again

RewriteRule settings/([a-zA-Z0-9_]+)/?$ settings/?path=$1 [NC,L,QSA]

Although, I don't know, if this is working at all, and how (in)efficient this is.

There is one caveat, you must check for REDIRECT_STATUS to prevent an endless loop.

Answer



Solution:

You can use these 2 rules in your .htaccess:

# remove path= parameter from query string, if it exists
RewriteCond %{THE_REQUEST} \?(.*&)?path=[^&]*(?:&(.*))?$ [NC]
RewriteRule ^settings/. %{REQUEST_URI}?%1%2 [L,R=301,NE,NC]

# your existing rule
RewriteCond %{THE_REQUEST} \?(.*&)?path=[^&]*(?:&(\S*))? [NC]
RewriteRule ^settings/ %{REQUEST_URI}?%1%2 [L,R=302,NE,NC]

RewriteCond %{QUERY_STRING} !(?:^|&)path= [NC]
RewriteRule ^(settings)/(\w*)/?$ $1/?path=$2 [NC,L,QSA]

Source