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 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 求螺旋焊缝的图像处理
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi
  • ¥20 win10修改放大文本以及缩放与布局后蓝屏无法正常进入桌面
  • ¥15 itunes恢复数据最后一步发生错误
  • ¥15 关于#windows#的问题:2024年5月15日的win11更新后资源管理器没有地址栏了顶部的地址栏和文件搜索都消失了