Home > OS >  Htaccess and PHP Direction or routing
Htaccess and PHP Direction or routing

Time:09-16

The URL I want to achieve: https://example.com/VdnbzeHfua/ep1_mp4

Note : My page (index.php) is located in root folder

when I access this URL https://example.com/VdnbzeHfua/ep1_mp4 it should not look forward for sub folders

i will get and use the values in the URL with PHP (index.php in root folder) like this

<?php

$url      = $_SERVER['REQUEST_URI'];
................
........... 
?>

How to achieve this with php and .htaccess?

Please anyone help me solving this.

CodePudding user response:

You require a standard front-controller pattern, which can be achieved with a single directive in .htaccess:

FallbackResource /index.php

Any request that would otherwise trigger a 404 is passed to /index.php instead.

An alternative method (which is perhaps more commonly seen) is to use mod_rewrite instead. For example:

RewriteEngine On

RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . index.php [L]

Although this alone doesn't do anything more than the FallbackResource directive does above.

Both methods would require the DirectoryIndex to be set correctly, if not already (this will usually be set to index.php in the server config). For example, at the top of your .htaccess, before the existing directives:

DirectoryIndex /index.php

You seem to already have the PHP part resolved. ie. check the value of $_SERVER['REQUEST_URI'] in order to examine the requested URL, which incidentally will also contain the query string.

You can then include the necessary PHP files as required. For example, this could be something simple like:

if ($url == '/about') {
    include('content/about.php');
}

But can be made as complex as you like. Obviously an if construct won't scale to 1000s of pages.

  • Related