0

Really simple question about `.htaccess, slugs and rewriting urls.

If I have an article how can I replace the entire url in the address bar with something out of a database?

For example in my url I have /article.php?id=1 In ralation to the id of the article in this case with id 1, I have a field name in the database called 'art_url' which has a value of /article/my-url

How can I get that to become the address instead of /article.php?id=1 ?

I get a PHP error when I try to use this URL dev.mywebaddress.com/article/my-url/. Is there an issue in my PHP with the htaccess file? Here is my code:

    <?php
    if(!empty($_GET['art_url']))
    {
    $sql = "

    SELECT articles.id AS articleid, articles.art_title AS title,  articles.art_url AS art_url, articles.art_content AS content, campaigns.id, campaigns.camp_title AS camptitle
FROM articles
LEFT JOIN campaigns ON articles.art_campaign = campaigns.id

";
}
    // then do the query, etc....

$results = $db->query($sql);

if($results->num_rows) {
    While($row = $results->fetch_object()) {
        $camptitle = nl2br(htmlentities($row->camptitle));
        $title = nl2br(htmlentities($row->title));
        $content = nl2br($row->content);
        $art_url = ($row->art_url);
        echo "
        <H2>{$camptitle}</H2>
    <H3>{$title}</H3>
    <p>{$content}</p>



";
    }
} else {
    echo 'No Results';
}
?>

.htaccess file

    # Turn Rewrite Engine On
RewriteEngine On
#RewriteRule ^article/([0-9a-zA-Z-/]+) article.php?art_url=$1
shimmy
  • 109
  • 1
  • 1
  • 8

1 Answers1

0

You can add a 301 redirect within your PHP code. Look up the value of art_slug and then ..

<?php 
header("HTTP/1.1 301 Moved Permanently"); 
header("Location: http://www.yourdomain.com/".$art_slug); 
?>

Your .htaccess file could be set up to pick up XXX/YYY using this:

RewriteEngine on
RewriteRule ^([^/\.]+)/([^/\.]+)$ index.php?firstSlug=$1&secondSlug=$2 [NC,L,QSA]

You would then receive firstSlug=XXX and secondSlug=YYY at index.php

Chris
  • 4,672
  • 13
  • 52
  • 93