Apache URL Re-writing not functioning properly

.htaccess, apache, php, url-rewriting

Solution

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 "<a href=\"/news/$row[id]\">  ". substr($row['title'], 0,26)."...</a><br/>".; }
}

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 "<a href=\"$url\">  ". substr($row['title'], 0,26)."...</a><br/>".; }
}

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.

Problem

I am trying to use apache-rewrite rule to convert the below URL: `http://localhost/foo/bar/news.php?id=24` Into this format: `http://localhost/foo/bar/news/foo-bar` The number `24` is an `id` of a random row from a MySQL table, which also contains `title` and `content` fields. ``` MariaDB [blog]> select * from articles; +----+---------+----------+ | id | title | content | +----+---------+----------+ | 1 | foo-bar | bla bla | +----+---------+----------+ 1 row in set (0.00 sec) ``` I have the following rule inside my `.htaccess`: ``` RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-l ^news/([A_Za_z0_9_]+)$ DIRECTORY/AID/news.php?id=$1 [QSA,L] ``` I also have a php code that generates a link like this: ``` $link = "<a href='news.php?id={$row['id']}'></a>"; echo $link; ``` However, I can't get the rewrite rule to change the path as the desired end result.

Original source