0

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);
Kush
  • 755
  • 7
  • 22
  • 1
    you'd want a negative lookahead assertion to disallow any `/` in the captured text. Check out: http://serverfault.com/questions/120971/regex-negative-look-ahead-is-not-working-for-mod-rewrite-between-different-apach – Marc B Mar 05 '13 at 16:04

1 Answers1

1

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.

Olaf Dietsche
  • 72,253
  • 8
  • 102
  • 198
  • Thanks. This works like a charm, but can you explain how this works ? or provide me a reference link ? – Kush Mar 06 '13 at 13:04
  • @KushSharma I tried to explain the regex a bit, I hope it makes it clear enough. There's some info on regex at the Apache website, but you can look at any website describing regular expressions or PCRE. – Olaf Dietsche Mar 06 '13 at 13:39