I am using htaccess to hide GET variables from the URL. I am having a problem. Myy project structure is something like this:
--project
index.php
/views
login.php
example.php
/user
dashboard.php
So, when I use something like "localhost/project/login", I am correctly redirected to the login.php page. But when I do something like "localhost/project/user/dashboard", I get an Apache generated 404 Not Found response.

This is what I am using in PHP to include the pages with the GET variables:
PHP code:
<?php
if(isset($_GET['page'])) {
$page = $_GET['page'].'.php';
if(is_file('views/'.$page)) {
include 'views/'.$page;
} else {
echo 'Page does not exist';
}
?>
htaccess file:
RewriteEngine on
RewriteRule ^([A-Za-z0-9-] )/?$ index.php?page=$1 [NC]
Can anybody give me some guidance? I don't have experience with .htaccess files
CodePudding user response:
RewriteRule ^([A-Za-z0-9-] )/?$ index.php?page=$1 [NC]
I'm assuming your .htaccess file is located in the /project subdirectory (for the localhost/project/login URL to be successfully matched and routed by your PHP code).
However, the regex in the RewriteRule directive does not match the request localhost/project/user/dashboard, because the regex does not match user/dashboard since the regex does not permit slashes (except at the end of URL-path). So the request simply drops through to an Apache 404.
You need to permit slashes in the RewriteRule pattern, which you could do by including a slash inside the character class. For example:
RewriteRule ^([/A-Za-z0-9-] ?)/?$ index.php?page=$1 [L]
The quantifier needs to be made non-greedy so as not to consume the optional trailing slash.
NB: The NC flag is not required here, but the L flag is (if you later add more directives).
