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

Redirect - 4 total parameters


@anubhava and @RavinderSingh13 have continued to help me learn and progress to where I am today with this script. This is what I have so far:

##1st rule with one parameter: $id--
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]

##Parameters are $id and $class
RewriteCond %{THE_REQUEST} \s/file\.php\?id=(\d+)&class=(\w+-class)\s [NC]
RewriteRule ^ /directory/%1/%2? [R=301,L]
RewriteRule ^directory/(\d+)/(\w+-class)/?$ /directory/file.php?id=$1&class=$2 [NC,L,QSA]

##Rule with two parameters: $id and $name--
RewriteCond %{THE_REQUEST} \s/file\.php\?id=(\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]```

Now, I would like to add one more rule with only one parameter instead of two. However, this parameter uses PHP $_GET['name'] in the url. I am trying to add one more rule that rewrites http://IPADDRESS.com/file.php?name=JohnDoe to http://IPADDRESS.com/newdirectory/JOHNDOE.

Thank you!


Solution

  • With your shown samples please try following. Please make sure to clear browser cache before testing your URLs.

    RewriteEngine ON
    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]
    
    ##Parameters are $id and $class
    RewriteCond %{THE_REQUEST} \s/file\.php\?id=(\d+)&class=(\w+-class)\s [NC]
    RewriteRule ^ /directory/%1/%2? [R=301,L]
    RewriteRule ^directory/(\d+)/(\w+-class)/?$ /directory/file.php?id=$1&class=$2 [NC,L,QSA]
    
    ##Rule with two parameters: $id and $name--
    RewriteCond %{THE_REQUEST} \s/file\.php\?id=(\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]
    
    ##Rule with two parameters: $name--
    RewriteCond %{THE_REQUEST} \s/file\.php\?name=(\S+)\s [NC]
    RewriteRule ^ /directory/%1? [R=301,L]
    RewriteRule ^directory/([^/]*)/?$ /directory/file.php?name=$1 [NC,L,QSA]