Andrea
Andrea

Reputation: 3

Rewriting the URL with htaccess (apache)

I have an website where in the homepage are displayed multiple articles. Every article has a link and when I click on it I pass the Id, the date and the title as parameters through the URL to "article.php" page. When I'm on the article page I recognize which article is by the Id and then I display the content.

But my problem is: when I open the "article.php" page my URL looks like this

http://127.0.0.1/Andrea/mySite/article.php?id=21&date=02%20march%202017%title=Basket%20NBA:%20Bulls-Warriors.%20Analysis

I have created the .htaccess file and I'm able to redirect people to other pages so the rewrite is enabled, what I'm searching is to change the URL from the above to something like this

http://127.0.0.1/Andrea/mySite/2017/03/02/basket-nba-bulls-warriors

So I want to remove the "Analysis" part after the point and "article.php" from the URL, the date to switch like if it was folders and the title to be written with scores between the words.

I have tried

RewriteEngine on
RewriteRule ^id/([A-Za-z0-9-]+)/?$ article.php?id=$1 [NC]

To remove "article.php" and add id between slashes but it doesn't seem to work.

Thanks in advice to everyone who will help me.

Upvotes: 0

Views: 101

Answers (1)

Shahzaib Chadhar
Shahzaib Chadhar

Reputation: 178

The .htaccess route with mod_rewrite

Add a file called .htaccess in your root folder, and add something like this:

RewriteEngine on
RewriteRule ^/?Some-text-goes-here/([0-9]+)$ /picture.php?id=$1

This will tell Apache to enable mod_rewrite for this folder, and if it gets asked a URL matching the regular expression it rewrites it internally to what you want, without the end user seeing it. Easy, but inflexible, so if you need more power:

The PHP route

Put the following in your .htaccess instead:

FallbackResource index.php

This will tell it to run your index.php for all files it cannot normally find in your site. In there you can then for example:

$path = ltrim($_SERVER['REQUEST_URI'], '/');    // Trim leading slash(es)
$elements = explode('/', $path);                // Split path on slashes
if(empty($elements[0])) {                       // No path elements means home
    ShowHomepage();
} else switch(array_shift($elements))             // Pop off first item and switch
{
    case 'Some-text-goes-here':
        ShowPicture($elements); // passes rest of parameters to internal function
        break;
    case 'more':
        ...
    default:
        header('HTTP/1.1 404 Not Found');
        Show404Error();
}

This is how big sites and CMS-systems do it, because it allows far more flexibility in parsing URLs, config and database dependent URLs etc. For sporadic usage the hardcoded rewrite rules in .htaccess will do fine though.

Upvotes: 3

Related Questions