4

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.

1 Answer 1

8

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.

Sign up to request clarification or add additional context in comments.

3 Comments

This seems to work, but I currently have my site in a subdirectory and it takes the name of the directory as the first parameter. I tried changing the rewritebase but can't get it to work. Ideally it would work the same in my dev environment where the site resides in a sub directory as in the production environment where the site resides in the root.
Ok, I think i got to work. Changed the condition to: RewriteCond %{REQUEST_URI} ^/[^/]+/?([^/]*)?/?([^/]*)?/?([^/]*)?/?([^/]*)?/? [NC] for my dev environment. I'll just change it back once I move to production.
@Splatbang Okay. I was just leaving a comment to suggest the modifications. Glad you made it work.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.