Search code examples
.htaccess

htaccess rewrite with two paramaters


I am using the following htaccess rewrite which works great for 1 parameter, such as https://example.com/admin

RewriteEngine On

#Rewrite specific url rewriting page
RewriteRule ^([a-zA-Z0-9_-]+)$ index.php?key=$1
RewriteRule ^([a-zA-Z0-9_-]+)/$ index.php?key=$1

But I want the option of having it one level deeper. https://example.com/admin/profile

RewriteEngine On

#Rewrite specific url rewriting page
RewriteRule ^([a-zA-Z0-9_-]+)$ index.php?key=$1&keytwo=$2
RewriteRule ^([a-zA-Z0-9_-]+)/$ index.php?key=$1&keytwo=$2

But this does not even hit my index.php for me to pick up and translate the values.


Solution

  • Your matching pattern does not match the URL with two parameters. Look at the group of characters you allow for that parameter in the pattern: letters, digits, underscore and dash. That won't match a slash. So the pattern won't match requests to URLs with such a dash in the middle.

    You need to adapt your matching pattern. Try something like that:

    RewriteEngine On
    RewriteRule ^/?([a-zA-Z0-9_-]+)/?$ index.php?key=$1 [L]
    RewriteRule ^/?([a-zA-Z0-9_-]+)/([a-zA-Z0-9_-]+)/?$ index.php?key=$1&keytwo=$2 [L]
    

    The first rule matches requested URLs with a single parameter that contains letters, digits, underscores and dashes. It matches with or without a trailing slash in the URL. The second rule does the same for a requested URLs with two parameters separated by a slash.

    The [L] flag terminates that round of rewriting if the pattern matches. None of the pattern patches an already rewritten request (matches index.php) which is why this does not end in an endless rewriting loop.

    The trailing /? accepts a trailing slash, while the pattern still matches if it is missing. That way you do not need two rules for those two cases.

    The leading /? makes the pattern match both, absolute and relative paths. Which means that the same rule can be used in the central http server's host configuration (which is preferred for a number of reasons) or in a distributed configuration file (typically called .htaccess which comes in handy as a last option if there is no access to the actual configuration).