Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating user friendly URLs with .htaccess file

I have two php files in the same directory posts.php and postdetails.php. The posts.php page lists all posts and postdetails.php displays the post when the postid is set like: postdetails.php?id=3

I want to make the posts and postdetails pages accessible without the .php and also add a trailing forward slash like:

instead of www.domain.com/posts.php

I'd have:

www.domain.com/posts/

I used this:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^/]+)/$ $1.php
RewriteRule ^([^/]+)/([^/]+)/$ /$1/$2.php
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !(\.[a-zA-Z0-9]{1,5}|/)$
RewriteRule (.*)$ /$1/ [R=301,L]

and now I can access posts.php the way I want, as in: www.domain.com/posts/

but now all the posts show links as www.domain.com/posts/postdetails.php?id=NUMBER

The thing is I'd like them to also like they are in the posts subdirectory but I can't seem to make it work.

I also want to change the id to slug

So that I'd have something like postdetails.php?slug=this-is-a-post and have it proprerly rerouted to www.domain.com/posts/this-is-a-post/

and I'm using this function to create my slugs.

function createSlug($str)
{
    if($str !== mb_convert_encoding( mb_convert_encoding($str, 'UTF-32', 'UTF-8'), 'UTF-8', 'UTF-32') )
        $str = mb_convert_encoding($str, 'UTF-8', mb_detect_encoding($str));
    $str = htmlentities($str, ENT_NOQUOTES, 'UTF-8');
    $str = preg_replace('`&([a-z]{1,2})(acute|uml|circ|grave|ring|cedil|slash|tilde|caron|lig);`i', '\\1', $str);
    $str = html_entity_decode($str, ENT_NOQUOTES, 'UTF-8');
    $str = preg_replace(array('`[^a-z0-9]`i','`[-]+`'), '-', $str);
    $str = strtolower( trim($str, '-') );
    return $str;
}

Any help please?

like image 328
angus Avatar asked May 04 '14 12:05

angus


1 Answers

Create a directory posts with an index-file (present a list of posts, link to the pretty url) and this .htaccess:

RewriteCond %{REQUEST_URI} ^/posts/[^/]+/.*$
RewriteRule ^/posts/([^/]+)/$ postdetails.php?slug=$1 [QSA,L]

The pretty url

in this pattern:
http://www.example.com/posts/slug/

e.g.:
http://www.example.com/posts/keywords-are-here/

In the file postdetails.php you can evaluate the param $_GET['slug'].

like image 93
Phil Avatar answered Oct 07 '22 17:10

Phil