How to Do Url Rewriting in PHP

How to do URL re-writing in PHP?

A Beginner's Guide to mod_rewrite.

Typically this will be nothing more than enabling the mod_rewrite module (you likely already have it enabled with your host), and then adding a .htaccess file into your web-directory. Once you've done that, you are only a few lines away from being done. The tutorial linked above will take care of you.

Just for fun, here's a Kohana .htaccess file for rewriting:

# Turn on URL rewriting
RewriteEngine On

# Installation directory
RewriteBase /rootDir/

# Protect application and system files from being viewed
RewriteRule ^(application|modules|system) - [F,L]

# Allow any files or directories that exist to be displayed directly
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

# Rewrite all other URLs to index.php/
RewriteRule .* index.php/$0 [PT,L]

What this will do is take all requests and channel them through the index.php file. So if you visited www.examplesite.com/subjects/php, you may actually be visiting www.examplesite.com/index.php?a=subjects&b=php.

If you find these URLs attractive, I would encourage you to go one step further and check out the MVC Framework (Model, View, Controller). It essentially allows you to treat your website like a group of functions:

www.mysite.com/jokes

public function jokes ($page = 1) {
# Show Joke Page (Defaults to page 1)
}

Or, www.mysite.com/jokes/2

public function jokes ($page = 1) {
# Show Page 2 of Jokes (Page 2 because of our different URL)
}

Notice how the first forward slash calls a function, and all that follow fill up the parameters of that function. It's really very nice, and make web-development much more fun!

URL rewriting with PHP

You can essentially do this 2 ways:

The .htaccess route with mod_rewrite

Add a file called .htaccess in your root folder, and add something like this:

RewriteEngine on
RewriteRule ^/?Some-text-goes-here/([0-9]+)$ /picture.php?id=$1

This will tell Apache to enable mod_rewrite for this folder, and if it gets asked a URL matching the regular expression it rewrites it internally to what you want, without the end user seeing it. Easy, but inflexible, so if you need more power:

The PHP route

Put the following in your .htaccess instead: (note the leading slash)

FallbackResource /index.php

This will tell it to run your index.php for all files it cannot normally find in your site. In there you can then for example:

$path = ltrim($_SERVER['REQUEST_URI'], '/');    // Trim leading slash(es)
$elements = explode('/', $path); // Split path on slashes
if(empty($elements[0])) { // No path elements means home
ShowHomepage();
} else switch(array_shift($elements)) // Pop off first item and switch
{
case 'Some-text-goes-here':
ShowPicture($elements); // passes rest of parameters to internal function
break;
case 'more':
...
default:
header('HTTP/1.1 404 Not Found');
Show404Error();
}

This is how big sites and CMS-systems do it, because it allows far more flexibility in parsing URLs, config and database dependent URLs etc. For sporadic usage the hardcoded rewrite rules in .htaccess will do fine though.

URL rewriting in PHP

http://localhost/april/video?category=Programming-Language&cat_id=2

This can be transformed into:
http://localhost/Programming-Language/2

(notice that I shifted cat_id to the end, since I suspected it to be a page number.)

This is accomplished by placing the following in your .htaccess:

RewriteEngine On
RewriteRule ^([^/]*)/([^/]*)$ /april/video?category=$1&cat_id=$2 [L]

Obviously you can then pick up the variables via $_GET request ($_GET['category'])

.htaccess url rewriting rule for multiple php files

This is probably close to what you are looking for:

RewriteEngine on
RewriteCond %{REQUEST_URI} ^/([^/]+)/
RewriteCond %{DOCUMENT_ROOT}/%1.php -f
RewriteRule ^/?([^/]+)/([0-9]+)/?$ $1.php?page=$2 [END]

That setup will work in the http servers host configuration and in dynamic configuration files (.htaccess style files), provided their interpretation is enabled at all (AllowOverride directive) and that the file is located at the correct location and readable for the http server.

If you are operating a really old version of the apache http server you may have to replace the END flag with the L flag...


A general hint: you should always prefer to place such rules inside the http servers host configuration instead of using dynamic configuration files (".htaccess"). Those files are notoriously error prone, hard to debug and they really slow down the server. They are only provided as a last option for situations where you do not have control over the host configuration (read: really cheap hosting service providers) or if you have an application that relies on writing its own rewrite rules (which is an obvious security nightmare).

$_GET and URL Rewriting for PHP

Yes, that will work as expected.

PHP URL Rewrite - No getting Query String Parameter

It looks like you have a conflict with MultiViews. You should disable MultiViews at the top of your .htaccess file:

Options -MultiViews

If MultiViews is enabled then when you request /CMS/listing/1, mod_negotiation will map the request to /CMS/listing.php (appending the file extension, without any URL parameter) before your mod_rewrite directive is able to process the request. (/1 is seen as additional pathname information or PATH_INFO on the URL.)

A URL like /CMS/listing?id=1 (without the file extension) will only work if MultiViews is enabled. In this case, the query string is already present on the URL.

htaccess url rewriting with multiple php vars in url

Try it like this, I am unsure about the character you are passing and also you need to pass id in url too for rewriting. Please let me know if it works.

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)/([\d]+)$ pn?title=$1&id=$2 [QSA,NC,L]


Related Topics



Leave a reply



Submit