Search code examples
regex.htaccessmod-rewriteurl-rewriting

Rewrite URL with htaccess (php)


I'm not the best with .htaccess so I hope someone here can help. I'm trying to rewrite a URL to look more clean.

Original URL: domain.com/admin/users?userid=<id>
What I want: domain.com/admin/users/<id>

I have tried this code but I'm getting a 404:

RewriteRule ^admin/users/([a-zA-Z0-9_-]+)$ users.php?userid=$1
RewriteRule ^admin/users/([a-zA-Z0-9_-]+)/$ users.php?userid=$1

Solution

  • The directory was omitted from the rewrite. The character class can also be simplified and the trailing slash can be made optional:

    RewriteRule ^admin/users/([-\w]+)/?$ admin/users.php?userid=$1
    

    A detailed write up of \w can be found here, http://regular-expressions.info/shorthand.html. In short:

    \w stands for “word character”. It always matches the ASCII characters [A-Za-z0-9_]

    regex101 can also be used, http://regex101.com/r/Px2vTE/1