Search code examples
php.htaccessmod-rewriterootsubdirectory

How to rewrite URL rules to the root folder but not its subdirectories?


I'm creating a vanity URL/ clean urls for my users. The .htaccess rewrite rules are working fine but I'm facing problem with the subdirectories.

Particularly like, when someone types example.com/user it works perfectly fine and fetch data from the page example.com/profile.php?username=user. But when somebody browse,example.com/subdirectory/user, this also shows the content of example.com/profile.php?username=user.

How can I limit the rewrite rules to only my root directory and not its subdirectory so that when someone browse example.com/subdirectory/user they will be redirected to 404 Not found as usual if there is no such file or folder in that subdirectory.

.htaccess code is as follows:

Options +FollowSymLinks
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^\.]+)/?$ profile.php?username=$1 [L]

Solution

  • [^\.]+ is a poor placeholder, that matches almost anything (including path segments).

    Since usernames are likely alphanumeric, \w+ is a better fit:

    RewriteRule ^(\w+)/?$ profile.php?username=$1 [L]
    

    Btw, typically you'd want more speaking paths like /user/name… rather than having a magic lookup in the site root.