PHP

SIMPLE PRETTY URL WITH PHP HTACCESS

(a quick example)

TURN ON REWRITE ENGINE RewriteEngine On RewriteBase / RewriteRule ^index\.php$ - [L]

CREATE HTACCESS FILE

01

DO NOT REWRITE HTTP AUTH REQUESTS RewriteRule .* - [E=HTTP_AUTHORIZATION :%{HTTP:Authorization}]

REDIRECT EVERYTHING TO INDEX.PHP RewriteRule . /index.php [L]

DO NOT REWRITE EXISTING FILES FOLDERS RewriteCond %{REQUEST_FILENAME} !-f RewriteCond  %{REQUEST_FILENAME} !-d

GET CURRENT URL PATH $path = parse_url(   $_SERVER["REQUEST_URI"],   PHP_URL_PATH );

INDEX.PHP PART A

02

SPLIT INTO ARRAY $path = explode("/", rtrim($path, "/\\"));

EXCLUDE BASE PATH define("URL_BASE", "/"); if (substr($path, 0, strlen(URL_BASE)) == URL_BASE) { $path = substr($path, strlen(URL_BASE)); }

INDEX.PHP PART B

03

"TRANSLATE" URL PATH TO FILE if (count($path)==1) {   $file = $path[0]=="" ? "index.html" :    $path[0] . ".html";  } else {   $file = implode("-", $path) . ".html";  }

04

LOAD REQUESTED PAGE if (file_exists($file)) {   require $file;  } else {   http_response_code(404);   require "404.html"; }

INDEX.PHP PART C