douyakao5308 2012-09-24 15:37
浏览 41
已采纳

使用.htaccess重写post.php?post_id = 20到/ post / this-is-the-title /

I am new to .htacces and for ages I have been trying to get my domain from:

www.domain.com/post.php?post_id=20

to something such as this:

www.domain.com/post/this-is-the-title/

As I said I am new to .htaccess but anything would help please! NOTE: I would be getting the titles of my blog posts from an SQL database somehow

  • 写回答

3条回答 默认 最新

  • duangan7834 2012-09-24 15:41
    关注

    If the page titles are database-driven (or otherwise dynamic), I don't see how you could get away with .htaccess rewrites. It would make more sense to use routing in your PHP script.

    I have written about an extremely simple routing method here. It's for people only getting into the subject, but you should be able to build a database-driven router based on that.

    Essentially, route all your traffic through index.php and there, get the request URI and decide what resources to load.

    [EDIT]

    Let me elaborate a bit, using the info from my blog post.

    Assuming you have your site set up and running, first direct the traffic to index.php. You do that in .htaccess and it can be done like this:

    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} -s [OR]
    RewriteCond %{REQUEST_FILENAME} -l [OR]
    RewriteCond %{REQUEST_FILENAME} -d
    RewriteRule ^.*$ - [NC,L]
    RewriteRule ^.*$ index.php [NC,L]
    

    Then, in index.php (or in a script that's called from index.php), you can get the request URI:

    $uri = $_SERVER["REQUEST_URI"];
    

    OK, so far so good. Now let's assume your database holds page content along with the page aliases. The uri will most probably be the page alias, so all you need to do is something like this:

    $pdo = new PDO(/* your db connection params */);
    $page = $pdo
        ->query("SELECT * FROM pages WHERE alias = :alias",
        array("alias" => $uri)
        )
        ->fetch();
    

    At this point you should have the page content corresponding to the title (or alias) in the URI string. All you need to do now is display it any way you want:

    echo $page["content"];
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 ensp路由器启动不了一直报#
  • ¥50 安卓10如何在没有root权限的情况下设置开机自动启动指定app?
  • ¥15 ats2837 spi2从机的代码
  • ¥200 wsl2 vllm qwen1.5部署问题
  • ¥100 有偿求数字经济对经贸的影响机制的一个数学模型,弄不出来已经快要碎掉了
  • ¥15 数学建模数学建模需要
  • ¥15 已知许多点位,想通过高斯分布来随机选择固定数量的点位怎么改
  • ¥20 nao机器人语音识别问题
  • ¥15 怎么生成确定数目的泊松点过程
  • ¥15 layui数据表格多次重载的数据覆盖问题