Search code examples
.htaccesshttp-redirectmod-rewriteurl-rewritingfriendly-url

.htaccess ModRewrite with 2 parameters


@anubhava provided an excellent answer for my previous question of doing an .htaccess internal rewrite with the below code, which worked for my one search query.


RewriteCond %{ENV:REDIRECT_STATUS} ^$
RewriteCond %{QUERY_STRING} id=([0-9]+) [NC]
RewriteRule ^file\.php$ /directory/%1? [R=301,L,NC]

RewriteRule ^directory/(\d+)/?$ /directory/file.php?id=$1 [L,QSA,NC]

I wanted to make this a separate question since my next question is slightly different. How could I adapt this to also work with two parameters? For instance, I would also like http://ipaddress/directory/file.php?id=47?name=value1 to redirect to http://ipaddress/directory/47/value1 name= can also be any combination of letters and numbers, like value1050, etc.

Thank you @anubhava for your previous answer above, and maybe there's a way to add on this second parameter as well?


Solution

  • Considering you are segregating your query string values in id=1234&name=value123 style, since passing 2 times query string will not be allowed, then you could try following, fix of your shown attempt.

    RewriteEngine on
    RewriteCond %{ENV:REDIRECT_STATUS} ^$
    RewriteCond %{QUERY_STRING} ^id=(\d+)&name=(.*)$ [NC]
    RewriteRule ^file\.php/?$ /directory/%1/%2? [R=301,L,NC]
    
    RewriteRule ^directory/(\d+)/(.*)/?$ /directory/file.php?id=$1&name=$2 [L,QSA,NC]
    


    2nd solution: Adding 1 more solution here, either use above OR use following one at a time only please.

    RewriteEngine on
    RewriteCond %{THE_REQUEST} \s/file\.php\?d=(\d+)&name=(\S+)\s [NC]
    RewriteRule ^ /directory/%1/%2? [R=301,L]
    RewriteRule ^directory/(\d+)/(.*)/?$ /directory/file.php?id=$1&name=$2 [NC,L,QSA]