0

My index.php file pulls down a list of articles from a database, the goal is the user can click on them to view the full article. The link looks like this:

echo "<tr><td colspan='2'><a href='"."article.php?type=".$type."&id=".$id."&title=".$title."'>".$title."</a></td></tr>";

Producing URL's like this:

http://example.org/article.php?type=news&id=2&title=second-article-test

All articles from the index.php file are linked to article.php in the same directory.

The goal is to make more friendly URLs appear like this:

http://example.org/news/2/second-article-test

I've been playing around with a number of .htaccess configurations including:

RewriteEngine On
RewriteCond %{REQUEST_FILE} !-f
RewriteCond %{REQUEST_FILE} !-l
RewriteCond %{REQUEST_URI} !^/article\.php [NC]
RewriteRule ^(.+)$ /article.php/$1 [L]

and

RewriteEngine On
RewriteCond %{REQUEST_URI} ^/article/?
RewriteCond %{REQUEST_FILE} !-f
RewriteCond %{REQUEST_FILE} !-l
RewriteRule ^(.*)$ article.php?type=$1&id=$2&title=$3 [QSA,L]

But I can't seem to get it working.

My 2 questions are:

  1. How do I change the variable GET links to be more friendly using example.org/type/id/title?
  2. How do I hide the article.php file I'm linking to in the URL?

I've tried about 20 variations and every time something gets messed up, if anyone knows how to fix any of this can you please try explain it so i'll know for next time, thanks!

Crizly
  • 971
  • 1
  • 12
  • 33

2 Answers2

2

You shouldn't put the logic of variable mapping into the .htaccess file.

Look at stackoverflow questions on how to hide the php extension, and then you need to compose a FrontController of some kind (you are going to need to parse $_SERVER['REQUEST_URI'] and determine where to unpack path elements into variables). But really, this has been done so many times you should look into a framework for doing this for you. If you want something really minimal look at Silex or Slim.

Community
  • 1
  • 1
Kris Erickson
  • 33,454
  • 26
  • 120
  • 175
1

You can play with this:

RewriteEngine On
RewriteCond %{REQUEST_URI} ^/?article/?
RewriteCond %{REQUEST_FILE} !-f
RewriteCond %{REQUEST_FILE} !-l
RewriteRule ^/?(.*?)/(.*?)/(.*?)/?$ article.php?type=$1&id=$2&title=$3 [QSA,L]
# example.org/type/id/title
Adrian B
  • 1,490
  • 1
  • 19
  • 31