开发者

pretty urls from database

I am trying 开发者_运维技巧get pretty urls on my site..right now they look like this:

www.site.com/tag.php?id=1

I want to change that to

www.site.com/tag/1/slug

my database table has ID,Title,Info,Slug

I read online about slugs,but being new to php found no luck,can anyone help me with this.


First create an .htaccess file with the following:

# Turn on rewrite engine and redirect broken requests to index
<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} !-l
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule .* router.php [L,QSA]
</IfModule>

Then, set the following code for router.php:

<?php

$segments=explode('/',trim($_SERVER['REQUEST_URI'],'/'),3);

switch($segments[0]){
    case 'tag': // tag/[id]/[slug]
        $_REQUEST['id']=(int)$segments[1];
        $_GET['id']=(int)$segments[1];
        $slug=$segments[2];
        require_once('tag.php');
        break;
}

?>

Further Clarification

Htaccess

The concept behind the htaccess is very simple. Instead of listening for URL patterns (as old htaccess software did), we simply reroute all traffic that would otherwise result in a 404 to router.php, which in turn takes care of doing what is required. There are 3 rewrite entries; for (sym)links, files and directories (/aaa is seen as a file while /aaa/bbb is seen as a folder)

Router

$_SERVER['REQUEST_URI'] looks like "/tag/1/slug". We first trim it against redundant slashes and then explode it in 3 items (so we don't affect slug, which might contain other slashes), print_ring the $segments (for tags/45/Hello/World) would look like:

Array
(
    [0] => tag
    [1] => 45
    [2] => Hello/World
)

Finally, since I see you want to redirect to tags.php?id=1, what you need to do is to set $_REQUEST['id'] and $_GET['id'] manually and load tags.php.


try this guide:

http://blogs.sitepoint.com/guide-url-rewriting/

// not my blog...

or this which seems better:

http://www.yourhtmlsource.com/sitemanagement/urlrewriting.html

EDIT:

this is for apache, as I assumed this was what you were using

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜