php.htaccessvanity-url

How to stop vanity url for sub-directory in domain


I have created a login interface where user can register there username. Now i wanted to give each user a vanity url like, example.com/user. I am using .htaccess rewrite conditions and php for that. Everything is working fine except when i try a url like example.com/chat/xx it displays a profile page with "xx" id. Instead it should have thrown a 404 page(thats what i want). I want that vanity url thing only works if a user input "example.com/user" not in sub directory like "example.com/xyz/user". Is this possible ?

htaccess --

RewriteEngine on
RewriteCond %{REQUEST_FILENAME}.php -f [OR]
RewriteCond %{REQUEST_FILENAME} -d 
RewriteRule ^([^\.]+)$ $1.php [NC]
RewriteCond %{REQUEST_FILENAME} >""
RewriteRule ^([^\.]+)$ profile.php?id=$1 [L]

Php used --

if(isset($_GET['id']))
// fetching user data and displaying it
else
header(location:index.php);

Solution

  • Then you must match on an URL-path without slashes / only

    RewriteEngine on
    RewriteRule ^/?([^/\.]+)$ profile.php?id=$1 [L]
    

    This regular expression ^([^\.]+)$ matches everything without a dot ., e.g.

    but it doesn't match

    This one ^/?([^/\.]+)$ works the same, except it disallows slashes / too. I.e. it allows everything, except URL-paths, containing either dot . or slash /.

    For more details on Apache's regular expressions, see Glossary - Regular Expression (Regex) and Rewrite Intro - Regular Expressions.