Quick and easy: Setting up clean URL's with PHP and htaccessPosted by Matt Thommes on October 13, 2009 | Post type: Gain So you've just bought the domain name, and pointed the DNS to your hosting provider. That magic little folder has just appeared via FTP, and is waiting for you to put stuff in it!
If you don't use a custom CMS to set up websites, it pays to know a quick approach to initially get pages on your site with clean URL's. Problem is, where do you start? It's quite daunting to design an entire site from scratch, and content management systems can be overkill for simple sites. If you just want to get some pages up there immediately, without too much configuration, here's a basic setup to get you started. Make sure your server runs Apache and PHP. In your root directory (in the screenshot above, it would be in the "html" directory), start by creating these files and folders:
This is your basic skeleton structure. Edit .htaccess fileNext, edit the RewriteEngine on RewriteRule !\.(gif|jpg|ico|css|js|txt)$ index.php Here we've enabled mod_rewrite, which is a powerful URL transformer. What we've done is told the system to redirect every request to So, if I visit this URL for your site:
It will load
It will still load As you can see, regardless of what directory request is made, the same script is loaded. Edit index.php fileTo start out your site, you probably want a few pages up there, with clean URL's, such as:
or:
Go ahead and open up
<?php
if (substr($_SERVER["REQUEST_URI"], -1, 1) != "/") $_SERVER["REQUEST_URI"] .= "/";
$url_array = explode("/", $_SERVER["REQUEST_URI"]);
array_shift($url_array);
array_pop($url_array);
?>
Here we've created an array containing "pieces" of the URL. For the URL Array ( [0] => "signup" ) How about this URL from earlier: Array ( [0] => "abc", [1] => "def", [2] => "ghi", [3] => "jkl", [4] => "mno", [5] => "p" ) As you can see, each "folder" in the URL is a separate array item. This will allow us to include the necessary page, based on the directory path in the URL. Add include fileNow, let's include the actual file content, based on the URL. In include "includes/" . $url_array[0] . ".php"; Remember our In our "includes" directory (the directory created initially), create a file called "signup.php". Now, whenever someone visits You now have clean URL's, with minimal setup! About the author(s)Matt Thommes is an independent publishing enthusiast, mobile blogger, content creator, informative writer, web developer from a suburb of Chicago. Never one to conform, Matt intends to promote the effect the web has on our lives, in an effort to intensify, instruct, and clarify all that is happening around us. Comments
|
Quick Link to this postTTIP.me/2226 |