views:

191

answers:

4

Ugh.. mod_rewrite makes me feel stupid. I just haven't wrapped my brain around it yet. :/

I have this url:

http://example.com/a/name/

...that I want to point here:

http://example.com/a/index.php?id=name

...where name is what is getting passed to index.php as the id argument.

Anything I've tried results in either a 404 or a 500.. :(

+1  A: 

To start you off:

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !index.php
RewriteRule ^/?a/([^/]+)/?$ /a/index.php?id=$1 [QSA,L]

If one rewrite tutorial doesn't work for you, try another.

Edit: excluded index.php as per Gumbo's suggestion

outis
Results in 500 error with this: Request exceeded the limit of 10 internal redirects due to probable configuration error.
Ian
Ah, this is just because its trying to rewrite the rewritten URL.. if I start from, say ^/?aa/ then it works fine. Thanks!
Ian
@Ian You have to exclude the file you are rewriting the request to.
Gumbo
+1  A: 

Maybe something along the lines of

RewriteEngine on
RewriteBase /a/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)/?$ index.php?id=$1 [L,QSA]

would do the trick.

laalto
+1  A: 

I suggest you take a look at this URL:

http://www.dracos.co.uk/code/apache-rewrite-problem/

The presented solutions will work, but there are some caveats explained in the URL, mainly regarding ? and # in the URLs themselves.

Vinko Vrsalovic
+2  A: 

If you want the trailing slash to be optional, you have to exclude the file you are rewriting the request to. Otherwise you will have a nice infinite recursion.

RewriteEngine on
RewriteCond %{REQUEST_URI} !^/a/index\.php$
RewriteRule ^/a/([^/]+)/?$ /a/index.php?id=$1 [L]

Here any request that starts with /a/… but it not /a/index.php is rewritten to /a/index.php.

But if the trailing slash is mandatory, there is no need to exclude the destination file:

RewriteEngine on
RewriteRule ^/a/([^/]+)/$ /a/index.php?id=$1 [L]
Gumbo