Question

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.. :(

Was it helpful?

Solution

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

OTHER TIPS

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]

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.

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top