Jonathan Clark
Jonathan Clark

Reputation: 20538

Vanity URLs using PHP and htaccess

I am developing an app using PHP and I would like my users to be able to use their own vanity URLs.

In this format:

http://example.com/username

For example:

http://example.com/myCoolUsername

If I use this URL now the server thinks it is a folder but I know I should use a .htaccess file in a way but I do not know what content I should use in that file.

Upvotes: 1

Views: 2277

Answers (2)

user562854
user562854

Reputation:

This rule will rewrite http://domain.com/username to user.php with username as GET parameter (name).

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /user.php?name=$1

To test, create a file named user.php in your directory root ant put that in your file:

Access http://domain.com/blablaName123 and if everything works fine you should see string(13) "blablaName123"

Upvotes: 3

Michael Berkowski
Michael Berkowski

Reputation: 270677

This assumes your index.php receives a $_GET['username'] to map to their vanity URL:

RewriteEngine On

# Make sure you only match on files/directories that don't actually exist
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

# Rewrite the first part after the `/` into a `username` parameter
RewriteRule ^(.+)$ /index.php?username=$1 [L,QSA]

Upvotes: 0

Related Questions