views:

24

answers:

2

Hello,

I want to use profile URLs on my site such as xyz.com/username

I am using the follow code:

RewriteRule ^([a-zA-Z0-9_-]+)$  index.php?p=profile&u=$1 [L,QSA]

RewriteRule ^([a-zA-Z0-9_-]+)/$ index.php?p=profile&u=$1 [L,QSA]

My question is... How can I use it like this, and keep the access to other links such as xyz.com/forums, xyz.com/friends, etc..

Thank you.

+1  A: 

You can try using a condition:

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([a-zA-Z0-9_-]+)/?$ index.php?p=profile&u=$1 [L,QSA]

The -f and -d are flags for "is a file" and "is a directory" respectively. ! negates that. Your rewrite should only happen for urls that don't actually exist in your web root. You'll probably want to add an initial condition to match against your username format so you don't stomp on every potential 404 error.

You could prepend the following, too:

RewriteCond %{REQUEST_URI} ^/[a-zA-Z0-9_-]+/?$

So you'll only match /adsfasdfasdf instead of /something/that/doesn't/exist

jasonbar
+1 but maybe explain in a bit more detail what -f and -d do?
Pekka
A: 

Use this:

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([a-zA-Z0-9_-]+)/?$ index.php?p=profile&u=$1 [L,QSA]

It checks whether the requested file is a directory or file, and if not passes it off to index.php

You can also put a ? after the / to make it optional (combining your two rules).

Blair McMillan