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.
First of all, you would need to change the href in the html, to give the new url format
The will generate urls like
http://localhost/news/24Note that I removed the
/DIRECTORY/AIDfrom 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_titletype of url. Because there is no correlation betweenthis_is_article_titleand the id24, 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_titleFirst the php part
Next comes the htaccess part.
That should do it I think.