Home > Mobile >  Generic way to rewrite external /api/entity/1 URL to internal /api/entity.php/1 (or /api/entity.php?
Generic way to rewrite external /api/entity/1 URL to internal /api/entity.php/1 (or /api/entity.php?

Time:11-17

With a API I'm trying to make in PHP I currently have these rewrite rules setup in the .htaccess file for the root directory of the API:

# Remove the php extension from the filename
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^\.] )$ $1.php [NC,L]

This is so that requests to the API appear more "RESTful" - so instead of api/entity.php?id=5 it would be api/entity?id=5 - I'd like to go a step further though, and allow a request URL like api/entity/5 to successfully rewrite to api/entity.php/5 or api/entity.php?id=5.

I was experimenting with an apache rewrite rule something like this, where it has regex to detect a path like entity/{any number here}

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^\.] )$ $1.php [NC]
RewriteRule ^(. )(\/\d )$ $1.php$2 [NC,L]

Where it would match entity/5 in two captures with entity and /5 and would then internally direct that to entity.php/5 - at which point in the php file I could do an explode on the request URI or something similar to that to get the value from the path.

But I don't really know enough about apache rewrites to fully implement this, as this rule doesn't work for whichever reason. I'm aware I could write hardcoded rewrite rules for each directory I would like to behave like this, but I'd really rather keep this generic.

If there is no real way to achieve what I want to here, then I'd rather just stick to paths like api/entity?id=5 than need to write a whole bunch of rewrite rules.

I was thinking as well, if there is a way to detect when a request doesn't match a directory (which would be what happens by default with a path like api/entity/5?) - it runs a different rewrite in this case - without running the first and causing it to try and write the now internally pointed URL, but again, I'm not sure how to go about implementing this.

Can someone with more experience point me in the right direction?

CodePudding user response:

As Chris Hass highlighted, in this case implementing a PHP router of some variation probably makes more sense and is just easier.

Here are links to some examples I found for anyone in the future who stumbles onto this:

https://medium.com/the-andela-way/how-to-build-a-basic-server-side-routing-system-in-php-e52e613cf241

https://www.taniarascia.com/the-simplest-php-router/

https://www.educative.io/edpresso/how-to-create-a-basic-php-router

Obviously, if you're not intentionally using just PHP on its own like me, there's no reason you couldn't use a library or do this with Laravel etc to make your life even easier, why reinvent the wheel after all?

  • Related