Apache URL Re-writing not functioning properly

前端 未结 12 1480
春和景丽
春和景丽 2021-01-17 21:31

I am trying to use apache-rewrite rule to convert the below URL:

http://localhost/foo/bar/news.php?id=24

Into this

12条回答
  •  抹茶落季
    2021-01-17 22:14

    First of all, you would need to change the href in the html, to give the new url format

    function news_preview() {
    $query = "SELECT * FROM news ORDER BY id DESC LIMIT 5  ";
    $result = mysql_query($query) or die(mysql_error());
    while($row=mysql_fetch_array($result)) 
    {   
      echo "  ". substr($row['title'], 0,26)."...
    ".; } }

    The will generate urls like http://localhost/news/24

    Note that I removed the /DIRECTORY/AID from the url, as the htaccess suggest you want that to be url, as opposed to what you stated in the text.

    But now the get to the http://localhost/news/this_is_article_title type of url. Because there is no correlation between this_is_article_title and the id 24, the only way to achieve this is by either adding the id to the url too, or to have the php lookup the news-article with this title in the database.

    This last solution however has some problems, as the you can't just us the title in a url. You have to escape characters. Also you'll have to add a index for the title row in the DB for better performance.

    So I'll go with the first solution. We will generate urls like this

    http://localhost/news/24/this_is_article_title

    First the php part

    function news_preview() {
    $query = "SELECT * FROM news ORDER BY id DESC LIMIT 5  ";
    $result = mysql_query($query) or die(mysql_error());
    while($row=mysql_fetch_array($result)) 
    { 
      $url = "/news/$row[id]/".preg_replace('/[^a-zA-Z0-9-_]/', '_', $row['title']);  
      echo "  ". substr($row['title'], 0,26)."...
    ".; } }

    Next comes the htaccess part.

    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-l
    RewriteRule ^news/([0-9]+)/([A-Za-z0-9_-]+)$ DIRECTORY/AID/news.php?id=$1 [QSA,L]
    

    That should do it I think.

提交回复
热议问题