Creating vanity URLs in a LAMP configuration

What is the best way to create user urls in a LAMP configuration?

For example, a user profile page can be accessed as follows:

http://www.website.com/profile.php?id=1

Now, if the user enters a “vanity URL” for his profile, I would like the vanity URL to load the page above.

For example, if a user selects “i.am.a.user” as their vanity URL and their user ID in the database is 1, then http://www.website.com/profile.php?id=1 will be available at this URL and http://www.website.com/i.am.a.user .

I know the mod rewrites in .htaccess, but not sure how it works here.

As I mentioned, my site is located in PHP, MySQL, Linux and Apache.

Thank.

+3
source share
4 answers

Say there were specific URLs on your other pages that you could check, the following should help.

RewriteEngine on

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([a-zA-Z0-9-_]*)$ /profile.php?user=$1 [L]

This helps maintain current URLs by allowing users to use shortcuts. In addition, it RewriteRulewill only match URLs that do not contain /, which will help protect against unwanted redirects. In this way,

/i-am-a-user -> MATCHES
/i_am_a_user -> MATCHES
/i-!am-a-user -> NOT MATCHED
/i.am.a.user  -> NOT MATCHED
/i.am.a.user/ -> NOT MATCHED
/some/page/ -> NOT MATCHED
/doesnotexist.php -> NOT MATCHED
/doesnotexist.html -> NOT MATCHED

Hope this helps.

EDIT

I updated the rules above so that the actual files / directories are not redirected, and also make sure that any file .phpor .htmlnot is sent to profile.php.

+4
source

site.com/user/USERNAME:

- .htaccess:

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

, "user" profile.php URI $_GET['name']. , // .

site.com/USERNAME:

RewriteEngine on
# if directory or file exists, ignore
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/]+)$ profile.php?name=$1 [L]

.php , , URI (, www.site.com)

PHP

profile.php - :

if (!empty($_GET['name'])
    $user = ... // get user by username
else 
    $user = ... // get user by id
+4

.htaccess , php:

RewriteEngine on
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule (.*) router.php [NC,L]

router.php $_SERVER ['REQUEST_URI'], , , .

, URL-, , .

, router.php, , . google URL php, .

+1

, , apache RewriteMap, , . RewriteMap ( , ), , , script (Perl, PHP, ), .

, PHP, MySQL mod_rewrite PHP.

+1

All Articles