2

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]
MrWhite
  • 43,179
  • 8
  • 60
  • 84
Abhi
  • 65
  • 10
  • Sounds like you used some overly generic RewriteRule copypasta. Impossible to tell without showing that config and/or the rewrite.log – mario May 15 '19 at 07:02
  • Check the post again, I've updated the .htaccess code... – Abhi May 15 '19 at 07:10
  • add `RewriteBase /subdirectory/` – PHP Ninja May 15 '19 at 07:14
  • Possible duplicate of [What does RewriteBase do and how to use it?](https://stackoverflow.com/questions/21347768/what-does-rewritebase-do-and-how-to-use-it) – PHP Ninja May 15 '19 at 07:15
  • So what is wrong in the code what can I change in it so that subdirectories would not rewrite url! – Abhi May 15 '19 at 07:17
  • I just want the root folder to rewrite the url and not the subdirectories like **mysite.com/subdirectories/user** – Abhi May 15 '19 at 07:19
  • "But when somebody browse, `example.com/subdirectory/user`, this also shows the content of `example.com/profile.php?username=user`" - this statement was a little misleading, since according to the directives you posted it would have resulted in a rewrite to `example.com/profile.php?username=subdirectory/user`, not simply `username=user`. – MrWhite May 16 '19 at 22:05

1 Answers1

1

[^\.]+ 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.

mario
  • 144,265
  • 20
  • 237
  • 291