im building a site with lots of parameters. At the moment i'm using this Code in my .htaccess file:
Options +FollowSymLinks
RewriteEngine on
RewriteBase /epo
RewriteRule (.*)/(.*)/(.*)/(.*)/(.*)/$ index.php?section=$1&content=$2&site=$3¶m=$4¶m2=$5 [QSA]
RewriteRule (.*)/(.*)/(.*)/(.*)/$ index.php?section=$1&content=$2&site=$3&subsite=$4 [QSA]
RewriteRule (.*)/(.*)/(.*)/$ index.php?section=$1&content=$2&site=$3 [QSA]
RewriteRule (.*)/(.*)/$ index.php?section=$1&content=$2 [QSA]
RewriteRule (.*)/$ index.php?section=$1 [QSA]
RewriteCond %{REQUEST_URI} ^/[^\.]+[^/]$
RewriteRule ^(.*)$ http://%{HTTP_HOST}%{REQUEST_URI}/ [R=301,L]
I'm new to mod_rewrite, thats why this code is a mess. Is there any better way to deal with all these parameters? The last two lines are just there to add a "/" at the end in case there is none. Would be also great if someone could explain their code, so i can understand what i did wrong :)
Personally I redirect all request to a single file and then handle it from there.
RewriteRule ^(.*)$ index.php?path=$1 [QSA]
And then in index.php use something like
$params = explode('/', $_GET['path'];
$section = $params[0];
$content = $params[1];
$site = $params[2];
$subsite = $params[3];
//etc.
Keep in mind that you do need some extra validation on all parameters
It is similar to Hugo's example but without GET
param:
<IfModule mod_rewrite.c>
SetEnv HTTP_MOD_REWRITE On
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} -s [OR]
RewriteCond %{REQUEST_FILENAME} -l [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^.*$ - [NC,L]
RewriteRule ^.*$ index.php [NC,L]
</IfModule>
in PHP
you can do following:
$pathInfo = pathinfo($_SERVER['SCRIPT_NAME']);
$baseUrl = $pathInfo['dirname'];
$baseFile = $pathInfo['basename'];
$url = rtrim(str_replace([$baseUrl, '/'.$baseFile], '', $_SERVER['REQUEST_URI']), '/');
$method = strtolower($_SERVER['REQUEST_METHOD']);
$isModRewrite = array_key_exists('HTTP_MOD_REWRITE', $_SERVER);
Your url's can now look something like:
http://www.yourserver.com/param1/param2
OR (if mod rewrite is not enabled)
http://www.yourserver.com/index.php/param1/param2
In both ways the $url
variable looks like /param1/param2
You can do explode
on this string or feed a PHP routing library with this string for extracting your parameters.
PHP routing example libraries:
https://github.com/robap/php-router
https://github.com/deceze/Kunststube-Router