1

I have url given below

http://localhost/main20/pages/view.php?id=hello-world

and want it to be shown as

http://localhost/main20/hello-world

I know its done using .htaccess and have found something here URL rewriting with PHP but its not fulfilling my requirement as my text "hello-world" will be changing on every request. Its something similar that wordpress does.

Cœur
  • 37,241
  • 25
  • 195
  • 267
smarttechy
  • 852
  • 1
  • 9
  • 23

3 Answers3

2

i found a solution my self here is the code and this http://roshanbh.com.np/2008/03/url-rewriting-examples-htaccess.html link solved my issue.

 RewriteEngine On
 RewriteRule ^([a-zA-Z0-9_-]+)$ pages/view.php?id=$1
 RewriteRule ^([a-zA-Z0-9_-]+)/$ pages/view.php?id=$1
smarttechy
  • 852
  • 1
  • 9
  • 23
1

NOTE: I am assuming that in http://localhost/main20/ will have index.php if not then create one. It will look a like something http://localhost/main20/index.php.

Now your .htaccess file would be something.

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.+)$ index.php/$1 [NC,L]
Options All -Indexes

In your index.php

<?php
define('WEBROOT','http://localhost/main20/');

//assuming your url is "http://localhost/main20/hello-wolrd"

$link=$_SERVER['REQUEST_URI'];  
$linkArr=explode("/",str_replace(WEBROOT,"","http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']));
/*
    print_r($linkArr);
    will output

    Array ( [0] => hello-wolrd ) 
*/

//now chech if $linkArr[0] is empty or not

if(!empty($linkArr[0])) 
{   
    include("pages/view.php?id".$linkArr[0]);
}
?>

Hope this help you.

This is a good link for more information.

Archish
  • 850
  • 8
  • 32
0

I think this .htaccess should work for you. Put it in the same folder where index.php is

RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

RewriteRule ^([^/]+)$ pages/view.php?id=$1 [L,QSA,NC]
b0ne
  • 653
  • 3
  • 10
  • Ooops my bad, i didn't see that pages should be removed from link as well... Try it now – b0ne Jun 24 '16 at 06:55
  • I tested this code on my localhost (i created folders main20 and pages) and it works for me. Here is my directory structure: .: -rw-rw-r-- 1 root root 298 јун 24 08:58 index.php drwxrwxr-x 2 root root 4096 јун 24 08:45 pages ./pages: -rw-rw-r-- 1 root root 24 јун 24 09:02 view.php – b0ne Jun 24 '16 at 07:05
  • not for me found a solution here at point 4 http://roshanbh.com.np/2008/03/url-rewriting-examples-htaccess.html – smarttechy Jun 24 '16 at 07:07