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

Are 3 identical parameters possible with .htaccess?


@anubhava and @RavinderSingh13 have helped me tremendously so far in understanding more about .htaccess and rewrite rules. However, even though both the first rule (with one parameter: $id) and the second rule (with two parameters: $id and $name) works for rewriting the url, my third rule I attempted with also two parameters ($id and $class) fails, and does not rewrite the final url. Below is my entire file so far. I would like to add that the $class parameter is in the format of a-class, b-class, etc., so maybe that could be a contributor to the the rewrite not working? Thank you for helping me continue to learn thus far!

RewriteEngine on
--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]

--2nd rule with two parameters: $id and $name--
RewriteEngine on
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]

--My attempt at the third rule following the example from the second, but this rule fails. Parameters are $id and $class--
RewriteEngine on
RewriteCond %{THE_REQUEST} \s/file\.php\?id=(\d+)&class=(\S+)\s [NC]
RewriteRule ^ /directory/%1/%2? [R=301,L]
RewriteRule ^directory/(\d+)/(.*)/?$ /directory/file.php?id=$1&class=$2 [NC,L,QSA]

Solution

  • With your shown samples and considering class word will be there always in your 3rd url try following rules. Also you need not to write RewriteEngine ON many times, only 1 time starting of file is enough.

    RewriteEngine on
    ##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]