mkab mkab - 1 year ago 152
Apache Configuration Question

Using apache mod_rewrite to redirect to php file

I'd like to redirect the following url:

http://www.example.com/food/?p=11&q=22&r=33


to

http://www.example.com/food/api.php/DBNAME/?p=11&q=22&r=33


As you may have noticed,
DBNAME
is the name of a database.
With the API I'm using it is necessary to include it in the URL.

Here's a brief folder structure of my program:

food/
->include/
->models/
->.htaccess
->api.php
->config.php
->test.php


I tried writing the rules on the .htaccess file but I get an
Internal server
error.

My .htaccess file looks like this:

<IfModule mod_rewrite.c>
RewriteEngine on
RewriteRule ^(.*)$ api.php/DBNAME/$1 [L]
</IfModule>


I can get my head around achieving the redirection.
I also tried

RewriteRule ^food/(.*)$ api.php/DBNAME/$1 [L]


but this rule just lists the files in the directory food.

Any ideas?
Thanks!

PS: The query string is not just
p=11&q=22&r=33
it may use any letter or word such as type, quantity and so on.
p=11&q=22&r=33
is just an example.

Edit
From the link that @sanj provided I changed my .htaccess ffile to this

<IfModule mod_rewrite.c>
RewriteEngine on
RewriteCond %{REQUEST_URI} ^/food/?$
RewriteRule ^(.*)$ api.php/DBNAME/$1
</IfModule>


It works partially. Why partially?

I have two servers, one for testing and one for production. It works well on the testing server but not on the production server. I get an
Authorization Required
error. I believe it's due to the configuration in my .htaccess because if I remove the mod_rewrite module and access the url directly it works. Any ideas?

Found my mistake. The folder was protected by Basic Authentication. I needed to include login parameters in my code. I can't believe I overlooked that.

Answer Source

I think this will work:

<IfModule mod_rewrite.c>
    RewriteBase /food
    RewriteEngine on
    RewriteCond %{QUERY_STRING} /DBNAME/
    RewriteCond %{QUERY_STRING} (.*)
    RewriteRule ^$                index.php/DBNAME/?%1 [L]
</IfModule>
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download