foo.com/alice vs. foo.com/users/alice

…衆ロ難τιáo~ 提交于 2019-11-29 02:06:22

I would say it depends on how user centred your site is.

Sites like myspace are http://www.myspace.com/jim/ because the site entirely revolves around the user.

A blog or news site, however, where you can register but it isn't important or mandatory could benefit from

http://www.news.com.au/users/jim/

Do you think if you're doing a website with users you could benefit from the MVC design pattern, or at least a popular MVC framework which uses a router to direct URIs?

If that URI came through a Router, and then was sent to the UsersController, you could decide to either show the user's profile, or direct them to create that user. You would not need to mess around with mod_rewrite except to make one rule that directs all requests to non existent files to index.php (or whatever the default of your server side language is)

If you do want to use mod_rewrite, try these rules

RewriteEngine On
RewriteCond %{REQUEST_URI} !(home|contact|about) [NC] // this line may be incorrect
RewriteRule ^/users/([^/]+)/?$ userpage?user=$1 [NC,L]

Please note the leading Carat as suggested by Gumbo, so it only matches /users/ of the TLD only.

That will match anything like foo.com/users/bob with an optional trailing slash. It is case insensitive and will be the last rule applied.

If the request comes in and the $_GET['user'] does not exist in your DB, you could try something like this

$user = $_GET['user'];

if (!user_exists($user)) {

    header('Location: createnew?user=' . urlencode($user));
    exit();

}

Then on the createnew page, simply do something like this

<input type="text" name="username" value="<?php echo htmlspecialchars(urldecode($_GET['user'])); ?>" />

That will fill in the username automatically with the username they tried to access a profile with.

If you'd like to know more about PHP and MVC, try a Google search or ask a question here on Stack Overflow.

The following rules rewrite a URL of the form foo.com/bar to foo.com/userpage?user=bar conditional on bar not already being a file or directory on the server. Put the following in .htaccess:

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/]+)/?$ userpage?user=$1 [NC,L]
</IfModule>

As in Alex's answer, the userpage script should redirect to createnew if the user doesn't exist:

$user = $_GET['user'];
if (!user_exists($user)) {
  header('Location: createnew?user=' . urlencode($user));
}

(As Knuth says, beware of bugs in the above code -- I have only proved it correct, not tried it. I'll update this answer when I've actually confirmed it works.) PS: CONFIRMED!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!