Rewrite url parameters - change http: // myweb /? Dept = dept & app = app at http: // myweb / dept / app

I currently have a web application that I need to optimize and one of the methods or something I'm trying to achieve is this:

http: // myweb / dept / app

from

http: // myweb /? dept = dept & app = app

I am currently using PHP code for it:

if(empty($_REQUEST['dept'])) {     
 $folder = "apps/"; 
} else {    
 $folder = str_replace("/", "", $_REQUEST['dept']) . "/"; }    
  if(empty($_REQUEST['n'])) {     
     include('user/home.php'); 
     } else {     
           $app = $_REQUEST['n'];
          if(file_exists($folder.$app.".php")) {          
             include($folder.$app.".php");     
             } else  {                   
             include("global/error/404.php");    
             }
         }  

      

How to do it?

I am currently with a half:

RewriteRule ^([A-Za-z]+)$ /index.php?app=$1 

      

but that only overwrites part of it.

thank

+2


source to share


2 answers


The way that many frameworks follow one of the following rules:

RewriteRule ^(.*)$ /index.php?q=$1
RewriteRule ^(.*)$ /index.php

      

In the first case, you will get the query string in $ _GET ["q"].
In the second case, you need to get the query string from $ _REQUEST or something like that. (just do a few var_dumps until you find what you need).
Then you explode ("/") and you're all set.



See how TYPO3 , eZPublish , Drupal do it.

You must also add the following conditions so that the site can open your static files (for example images / css / js / etc). They tell apache not to rewrite if the url points to a location that actually matches the file, directoy or symlink. (You must do this before the RewriteRule directive)

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-l

      

+2


source


This should work:

RewriteRule ^([A-Za-z]+)/([A-Za-z]+)$ index.php?dept=$1&app=$2 [QSA]

      

You need the QSA part to add any GET parameters to the rewritten url.

You may find that it might be more flexible to rewrite everything to index.php and then handle the URL splitting there, eg.



.htaccess:

#only rewrite paths that don't exist
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

RewriteRule ^(.*)$ index.php/$1

      

PHP:

<?php
$parts = explode('/', $_SERVER['PATH_INFO']);
$dept = isset($parts[0]) ? $parts[0] : 'someDefault';
$app = isset($parts[1]) ? $parts[1] : 'anotherDefault';

      

0


source







All Articles