Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.htaccess mod_rewrite url with multiple optional parameters

I'm pretty new to this mod_rewrite business but I'd like to have a rule that allows me to accomplish the following:

localhost/module_name/ -> localhost/index.php?module=module_name
localhost/module_name/module_action -> localhost/index.php?module=module_name&action=module_action
localhost/module_name/module_action/parm1 -> localhost/index.php?module=module_name&action=module_action&parm_1=parm1
localhost/module_name/module_action/parm1/parm2 -> localhost/index.php?module=module_name&action=module_action&parm_1=parm1&parm_2=parm2

and so on. I managed to get module_name and module_action to work, but I can't figure out how get it to work with only a module or with multiple parameters. This is what I currently have:

RewriteEngine on
RewriteRule ([a-zA-Z]+)/([a-zA-Z]+) index.php?module=$1&action=$2
RewriteRule ([a-zA-Z]+)/([a-zA-Z]+)/([a-zA-Z]+)$ index.php?module=$1&action=$2&parm=$3

The first rule seems to work but it breaks apart on the second one.

Any help would be really appreciated.

like image 419
Splatbang Avatar asked Feb 18 '23 16:02

Splatbang


1 Answers

You may try this:

RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI}  ^/([^/]+)/?([^/]*)?/?([^/]*)?/?([^/]*)?/?   [NC]
RewriteRule .*    index.php?key1=%1&key2=%2&key3=%3&key4=%4  [L]

Maps silently

http://localhost/val1/ up to

http://localhost/val1/val2/val3/val4

To:

http://localhost/index.php?key1=val1 up to

http://localhost/index.php?key1=val1&key2=val2&key3=val3&key4=val4

Not incoming valN values are empty in the substitution URL.

index.php is considered a fixed string.

For permanent redirection, replace [L] with [R=301,L],

Maximum number of parameters = 4.

like image 101
Felipe Alameda A Avatar answered Apr 02 '23 03:04

Felipe Alameda A