Kush
Kush

Reputation: 749

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);

Upvotes: 0

Views: 179

Answers (1)

Olaf Dietsche
Olaf Dietsche

Reputation: 74078

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.

  • a
  • bcd
  • hello/how/are/you
  • chat/xx

but it doesn't match

  • test.php
  • hello.world
  • chat/xx.bar

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.

Upvotes: 1

Related Questions