pretty urls from database

独自空忆成欢 提交于 2019-12-12 12:26:46

问题


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.


回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/5796248/pretty-urls-from-database

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