0

Possible Duplicate:
Everything You Ever Wanted to Know about Mod_Rewrite Rules but Were Afraid to Ask?

I am trying to use the following .htaccess rewrite rules but it just does not work for some reason.

RewriteEngine On
RewriteRule ^/([^/]+)/([^/]+)(.*) /index.php?_controller=$1&_action=$2$3 [QSA,L]
RewriteRule ^/([^/]+)(.*) /index.php?_controller=$1$2 [QSA,L]

I would like a url like this:

http://name.local/someFolder/?_controller=aController&_action=anAction

To be converted to:

http://name.local/someFolder/aController/anAction

I am not sure why my rewrite rules wont work like I want them to, any help would be appreciated. Thanks!

gprime
  • 161
  • 1
  • 9
  • 1
    These rules do not make much sense: matching `([^/]+)(.*)` and then replacing by `$1$2` ?? It's the same as `(.+)` and `$1`. As I understand you want to place such rewrite rule in `/somefolder/.htaccess` -- am I correct? (I need to know this in order to write a rule without a need of modifying it later). – LazyOne Aug 26 '11 at 17:23
  • @LazyOne yes my .htaccess is in the /someFolder/ which is the webroot for the site. – gprime Aug 29 '11 at 15:40

1 Answers1

0

Such rewrite can be done like this:

Options +FollowSymLinks -MultiViews
RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/]+)/([^/]+)$ index.php?_controller=$1&_action=$2 [QSA,L]

It will rewrite (internal redirect) request for /first/second to /index.php?_controller=first&_action=second.

It will only work if you requesting non-existing resource. So, if you have such folder /first/second, then no rewrite will happen.


If you change pattern from ^([^/]+)/([^/]+)$ to ^([^/]+)/([^/]*)$, then it will also be applicable for this rewrite: /first/ to /index.php?_controller=first&_action= (notice that trailing slash is required here).


If you change pattern from ^([^/]+)/([^/]+)$ to ^([^/]+)/([^/]+)/?$, then both /first/second and /first/second/ (one with trailing slash) will trigger the rule.


If you change pattern from ^([^/]+)/([^/]+)$ to ^([^/]+)(/([^/]*))?$, then this single rewrite rule will match /first/second as well as /first/ as well as /first (obviously, if 2nd segment is not present, then action parameter _action= will be empty).

It is also possible to make trailing slash with 2 segments optional (i.e. /first/second and /first/second/ will be treated as the same (from rewriting point of view). For that -- change pattern to ^([^/]+)(/([^/]*))?/?$.

LazyOne
  • 3,014
  • 1
  • 16
  • 15