Try this:
- if the filename of what I'm asking is not a file (example: /post.php)
- if the filename of what I'm asking is not a folder (example / css)
- then take everything that comes as filename and pass it to post.php as id
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.+)$ post.php?id=$1 [L]
and you generate the url like this:
$url_dinamica = "/".$url_que_genero_dinamicamente;
If you give a blank screen there may be redirects due to other rules in the .htaccess
or silently fail the post.php
, in that case you have to go testing taking rules of .htaccess
, pulling var_dump
/ print_r
, etc ... to see where the error is.
A complete redirecting example for "pretty urls", simulating a DB in an array:
index.php
<?php require_once('falsaDB.php'); ?>
<html>
<head>
<title>Post Example Index</title>
</head>
<body>
<ul>
<?php foreach ($tablaPOSTS as $key => $value) : ?>
<li><a href="./<?php echo $value['slug'];?>" ><?php echo $key.". ".$value['titulo'];?></a></li>
<?php endforeach; ?>
</ul>
</body>
falsaDB.php
<?php
$tablaPOSTS = array(
array('ID'=>0, 'titulo'=>'Un enlace bonito', 'texto'=>'El texto de un enlace bonito'),
array('ID'=>1, 'titulo'=>'Un post cualquiera', 'texto'=>'El texto de un post cualquiera'),
array('ID'=>3, 'titulo'=>'Otra prueba de re escritura', 'texto'=>'El texto de otra prueba de re rescritura'),
);
// genero los slugs a partir del título,
// esto debería hacerse al insertar el registro
foreach($tablaPOSTS as $key=>$post):
$tablaPOSTS[$key]['slug'] = strToLower(str_replace(' ', '-', $post['titulo']));
endforeach;
// Simulo un select post from tabla where slug=$slug
function findPOSTbySlug($slug, $tabla){
$key = array_search($slug, array_column($tabla, 'slug'));
return ($key)?$tabla[$key]:"'$slug' NO ENCONTRADO";
}
?>
post.php
<?php require_once('falsaDB.php'); ?>
<html>
<head>
<title>Post Example</title>
</head>
<body>
<?php
$elSlug = $_REQUEST['id'];
$resultado = findPOSTbySlug($elSlug, $tablaPOSTS);
if (is_array($resultado)) :
?>
<h1><?php echo $resultado['titulo'];?></h1>
<p><?php echo $resultado['texto'];?></p>
<?php else : ?>
<p><?php echo $resultado;?></p>
<?php endif; ?>
<pre>
<?php print_r($resultado); ?>
</pre>
</body>
</html>
.htaccess
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.+)$ post.php?id=$1 [L]
- I changed the matching pattern to pass the "filename" to
post.php
as id
- In case you want to pass additional parameters for example
/otra-prueba-de-re-escritura?pagina=2
the pagina=2
you get it from $_SERVER["REQUEST_URI"]
which would be the original url untransformed.
- if it is shared hosting or there are several virtualhost you may have to add
RewriteBase /
just before the first RewriteCond
, sometimes it also has a rule with [R]
just before or one level higher.