Home > Blockchain >  .HTACCESS adding to slugs
.HTACCESS adding to slugs

Time:04-02

So, I'm currently building a REST API in PHP.

I managed to get slugs working for the most part. If I request /api/admin/v1/users/1, it will return the user I need. However, I also need to be able to add to it, e.g. /api/admin/v1/users/1/keys.

The HTACCESS file managing the slug is in the folder itself (/users/).

RewriteEngine On
RewriteRule ^(.*)$ user.php?slug=$1 [L]

I tried adding another line, but I think I messed up (I'm not that advanced with HTACCESS)

RewriteRule ^(.*)/keys$ keys.php?slug=$1 [L]

This didn't do anything, it still returns the user object.

CodePudding user response:

RewriteRule ^(.*)$ user.php?slug=$1 [L]
RewriteRule ^(.*)/keys$ keys.php?slug=$1 [L]

The first rule matches everything, so the second rule is never processed. But since the first rule matches everything it will also rewrite itself (to user.php?slug=user.php) on the second pass by the rewrite engine.

You can resolve these issues by making the regex more restrictive. From your example URL it looks like the slug is numeric - in which case you can restrict the regex to match digits (0-9) only.

For example:

RewriteRule ^(\d*)$ user.php?slug=$1 [L]
RewriteRule ^(\d )/keys$ keys.php?slug=$1 [L]

Note that the first rule also matches an empty URL-path, ie. no slug at all (as does your original rule). The second rule does not permit an empty slug (it would never match anyway).

CodePudding user response:

The second rule don't work because the L flag stay for: last - stop processing rules

So you need to edit to:

RewriteEngine On
RewriteRule ^(.*)$ user.php?slug=$1 [QSA, L]
RewriteRule ^(.*)/keys$ keys.php?slug=$1 [QSA, L]
  • Related