Creating Vanity URLs
I currently run a site where I want to give people the ability to make their own URLs. For example, here is my URL: http://www.hikingsanfrancisco.com/hiker_community/hiker_public_profile.php?community_member_id=2
You see, it is named just by id, which is uninteresting and also bad for SEO (not that it matters here).
Ideally I want my site members to also have their names in the URL. How i开发者_运维百科s that typically done? So in my case, it would be something like: http://www.hikingsanfrancisco.com/alex-genadinik and have the id hidden.
Is that possible? Any advice would be appreciated!
Thanks, Alex
you need router, see https://stackoverflow.com/questions/115629/simplest-php-routing-framework
Generally this is accomplished via the use of an htaccess file on a server with mod_rewrite (most Linux servers). An example might be like:
Options -Indexes
RewriteEngine On
RewriteRule ^([0-9a-zA-Z\-]+)$ $1.php
RewriteRule ^/(alex[\-]genadinik)$ /hiker_community/hiker_public_profile.php? community_member_name=$1
This implies that your hiker_public_profile.php script will need to accept "alex-genadinik" as $_GET variable "community_member_name," and then query the database via the name instead of the ID.
So you'd take the above code, save it in a file called ".htaccess," and then upload it to the root directory of your website. Learning regular expressions is recommended.
Code Igniter is a great MVC framework which provides configuration derived routes, which can easily be configured to send all requests through a common controller, where content can be dynamically pulled from a database and rendered.
Here is an example of a basic routing rule, which excludes request for users, students, and lessons, but routes all other request to a common content controller.
So if you request http://mydomain.com/hiking-and-camping-info, the url would be parsed, and hiking-and-camping-info would be looked up in the database and the related content pulled down.
Routing configuration:
$route['^(?!lessons|students|users|content).*'] = 'content';
and the content controller then grabs the url segment and finds the matching content and loads it:
class Content extends Controller {
function __construct() {
parent::Controller();
$this->load->model('Content_model', 'content');
}
function index() {
$content_url = $this->uri->segment(1);
$data['content'] = $this->content->get_content_by_name($content_url);
$this->load->view('content', $data);
}
}
精彩评论