iceteea
iceteea

Reputation: 1224

mod_rewrite $_GET

I have a FrontController expecting two $_GET params:

controller
action

A typical call to the site would look like this:

http://foo.bar/index.php?controller=start&action=register

What I want to do is to allow the user to visit this site by the following url:

http://foo.bar/start/register

What I've tried:

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteRule ^(.+)/(.+)$ index.php?controller=$1&action=$2 [L,QSA]
</IfModule>

Since this gives me 404 Errors it doesn't seem to work.

mod_rewrite itself is enabled on the server.

Upvotes: 1

Views: 196

Answers (2)

Mark N Hopgood
Mark N Hopgood

Reputation: 893

There are 2 parts to getting this working. If you are working with PHP and Apache, rewrite engine must be available on your server.

In your user folder put a file named .htaccess with these contents:

 RewriteEngine on
 RewriteCond %{REQUEST_FILENAME} !-d
 RewriteCond %{REQUEST_FILENAME} !-f
 RewriteRule . index.php [L]

Then your index.php you can use the REQUEST_URI server variable to see what was requested:

<?php
$path = ltrim($_SERVER['REQUEST_URI'], '/'); 
echo $path;
?>

If someone requested /start/register, then assuming all the above code is in the html root, the $path variable would contain start/register.

I'd use the explode function on $path using the / as a separator and pull the first element as register.

The rewrite code has the benefit of working with filenames and directory names.

Upvotes: 0

webbiedave
webbiedave

Reputation: 48887

The .htaccess you posted works for me:

// GET /cont1/action1

print_r($_GET);

/* output
Array
(
    [controller] => cont1
    [action] => action1
)
*/

You might want to try an absolute path to index.php rather than a relative one.

Regardless, that regex will result in:

// GET /cont1/action1/arg1

print_r($_GET);

/* output
Array
(
    [controller] => cont1/action1
    [action] => arg1
)
*/

You'd be better off doing:

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ /index.php?url=$1 [QSA,L]
</IfModule>

And having your index.php split up the $_GET['url'] into controller, action, args, etc...

Upvotes: 2

Related Questions