1
I’ve searched multiple sources for a way to correctly apply a simple rule in htaccess for user-friendly url interpretation.
At first I have the codes below:
.htaccess
RewriteEngine on
RewriteCond %(SCRIPT_FILENAME) !-f
RewriteCond %(SCRIPT_FILENAME) !-d
RewriteRule ^([^/]*)$ index.php?url=$1
RewriteRule ^([^/]*)/$ index.php?url=$1
index php.
<!DOCTYPE html>
<html>
<head>
<title>Home</title>
<meta charset="utf-8">
</head>
<body>
<h1>Home</h1>
<?php
$url = (isset($_GET['url'])) ? $_GET['url'] : '';
echo $url;
?>
</body>
</html>
Here are the results I got:
I hoped that the first would not present any text below 'Home', and in the second the word 'test' should be presented instead of 'index.php'.
Can anyone tell me what I’m doing wrong?
Try to put
[NC,L,QSA]
at the end ofRewriteRule
. By the way, you can do in only one line the two conditions:RewriteRule ^([^/]*)/?$ /index.php?url=$1 [NC,L,QSA]
– Woss
With this option, the server correctly recognizes when not sending a parameter, but when sending it seems that it disregards the rule and looks for a page with the sent name. It returns a 404 error.
– Gilberto Rodrigues
What parameter would that be?
– Woss
As my code explains: If you enter the 'localhost/site' url, the server understands that the get URL parameter would be empty. If you enter the url 'localhost/site/test', the server understands that the get URL parameter would be 'test'.
– Gilberto Rodrigues
Strange, because I tested it here and it worked perfectly.
– Woss
Accessing
localhost
has this result and accessinglocalhost/teste
has this result.– Woss
I don’t know why this path isn’t working on my server, but I was able to resolve by changing the rule to
RewriteRule . index.php [L]
and in PHP accessing the variablefilter_input(INPUT_SERVER, 'REQUEST_URI')
.– Gilberto Rodrigues