Is there a way to rewrite this url? [closed]

痴心易碎 提交于 2019-12-08 03:43:29

问题


I need to redirect all urls like these:

www.example.com/blog.php?id=29

to urls like these:

www.example.com/blog/29/this-is-a-blogpost

Where "This is a blogpost" is the title stored in the database.

Is there a way to rewrite these urls in this way ?


回答1:


Well mod_rewrite canot query your database and pull the title for the provided id from a DB table.

You'll need to pass id to a server side code (like a php script) in order to fetch & display title.

For ex look at the SO URL for this question: http://stackoverflow.com/questions/17239887/is-there-a-way-to-rewrite-this-url where it is passing both id and title. So you can have friendly URLs like:

http://www.example.com/blog/29/this-is-a-blogpost

If you decide to go by my suggestion then here is the code you will need in .htaccess:

Options +FollowSymlinks -MultiViews
RewriteEngine On

RewriteRule ^blog/([0-9]+)/([^/]*)/?$ /content.php?id=$1&title=$2 [L,QSA,NC]

Then in your content.php:

<?php
   $id    = $_GET['id'];
   $title = $_GET['title'];

   $dbTitle = // get title from Database query using $id
   ...
   if ($title != $dbTitle) {
      // redirect with 301 to correct /blog/<id>/<title> page
      header ('HTTP/1.1 301 Moved Permanently');
      header('Location: /blog/' . $id . '/' . $dbTitle);
      exit;
   }
   // rest of your script
?>



回答2:


What you ask is obviously impossible: the second url you want to redirect to contains data that is not present (known) in the original request. Where should that data come from inside the redirection process?

The other way round certainly is possible and often done.



来源:https://stackoverflow.com/questions/17239887/is-there-a-way-to-rewrite-this-url

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