Created
November 5, 2013 08:40
-
-
Save lutsen/7315723 to your computer and use it in GitHub Desktop.
Clean URL's:
Use .htaccess URL rewrite and PHP to get clean URL's.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#php_flag display_startup_errors on | |
#php_flag display_errors on | |
#php_flag html_errors on | |
# Just in case... | |
Options +FollowSymlinks | |
RewriteEngine on | |
# Force WWW | |
########### | |
# For SEO and general functioning of your website, it is often better | |
# to either remove or, in this case, force the www subdomain to your URL | |
# Check whether Host value is not empty | |
RewriteCond %{HTTP_HOST} !^$ | |
# Checks if Host value does not begin with www. | |
RewriteCond %{HTTP_HOST} !^www\. [NC] | |
# Check for HTTPS (%{HTTPS} is either on or off, so %{HTTPS}s is either ons or offs and in case of ons the s is matched) | |
RewriteCond %{HTTPS}s ^on(s)| | |
# Merges the information parts to a full URL | |
RewriteRule ^ http%1://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L] | |
# Rewrite | |
######### | |
# No URL rewrite for existing files | |
RewriteCond %{REQUEST_FILENAME} !-f | |
# No URL rewrite for existing directories | |
RewriteCond %{REQUEST_FILENAME} !-d | |
RewriteRule ^(.*)$ index.php [L] |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// Create clean URL's like this: | |
// - Script gets the path of the url | |
// - It tries to include a script with the same name in the directory "content" (or any other directory you specify) | |
// | |
// For example: Url: http://www.hoverkraft.nl/werk/mt-challenge | |
// File that gets included content/werk/mt-challenge.php | |
function removeCommonPath($first, $second, $char='/'){ | |
$first = explode($char, $first); | |
$second = explode($char, $second); | |
while (count($second)){ | |
if($first[0]==$second[0]){ | |
array_shift($first); | |
} else break; | |
array_shift($second); | |
} | |
return implode($char, $first); | |
} | |
function getPath() { | |
$path = removeCommonPath($_SERVER['REQUEST_URI'], $_SERVER['SCRIPT_NAME']); | |
// Remove trailing stuff we don't want | |
$path = rtrim($path, "/ \t\n\r"); | |
return $path; | |
} | |
$permalink = getPath(); | |
if ($permalink == '') { | |
require_once('content/home.php'); | |
} elseif (file_exists('content/'.$permalink.'.php')) { | |
require_once('content/'.$permalink.'.php'); | |
} else { | |
header('HTTP/1.0 404 Not Found'); | |
header('Location: http://www.hoverkraft.nl'); // 404 page goes here | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment