views:

1559

answers:

11

I am trying to implement URL rewriting in my PHP application. Can someone share a step by step procedure of implementing URL rewriting in PHP - MYSQL.

In my application I want to implement following URL rewriting, I want to redirect

1. http://example.com/videos/play/google-io-2009-wave-intro
2. http://example.com/videos/play/203/google-io-2009-wave-intro

to

1. http://example.com/videos/play.php?title=google-io-2009-wave-intro
2. http://example.com/videos/play.php?id=203

Please tell me how to implement both url rewriting in any of the above way.

Edited: please answer this in your answers >> One more thing which URL will be best according to SEO, management, application point-of-view out of the following two types.

1. http://example.com/videos/play/google-io-2009-wave-intro
2. http://example.com/videos/play/203/google-io-2009-wave-intro

Thanks,

+1  A: 

After reading comments and question once again, I've realized that my previous answer is not completely the thing your are looking for. So here some additions, if you want rewrite/redirect/proxy the URL addresses so for example then user types www.f1.com he will actually see www.f2.com, but domain will remain the same, you probably need to setup a reverse proxy using Apache for that. It act's similar to mod_rewrite.

Regarding the second part, since modern crawler also performing the URL link analyses I think your first option is better performance wise.

Previous answer:
And using PHP you can achieve redirection like:

<?php
// Here you can parse the current location
// and decide whenever you want to go
// if $_SERVER[ 'PHP_SELF'] some conditions then....
header('Location: http://www.example.com/');
?>

From php.net. Here more examples.

Artem Barger
Did you understand ma question correctly?
Prashant
According to your question, there is a good chance I'm not. So maybe it's worth put some clarification. You asked how you can redirect using PHP, I show you a sample, it's only hardcoded, but you can make a parsing before you writing the header and only then make decision.
Artem Barger
Ok, may be you misunderstood due to redirect, anyways, I am looking for URL rewriting which means if user enters URL in the browser like http://example.com/video/play/203/kjhjkhkjh then internally it should call play.php to get the response. which is called re-writing.
Prashant
-1 for ... huh? that is just for redirection. the question is about how to have pretty urls.
Gabriel Sosa
@Gabriel, the question isn't only about that.
Artem Barger
+6  A: 

You cannot do this with PHP alone. You'll need to look into mod_rewrite (assuming you are using apache).

Evert
Yes, I am using it.
Prashant
@jeroen you cant do this only with php because it is apache who drive the urls and apache will try to get the requested resource that it why mod_rewrite allow you to rewrite urls. that said you need some other layer besides php to make this
Gabriel Sosa
just realize... you can do it like index.php/mi-page, index.php/my-page-2 but you still having index.php in url and the goal here is remove it
Gabriel Sosa
Yes, silly, I wasn´t thinking....
jeroen
Although... A very very very bad but possible php-only solution would be to have the re-writing done in your 404 error-page. Extremely SEO unfriendly, but just hypothetically :-)
jeroen
You'd be surprised. It's been done by at least one high-profile software package.
Jim Puls
+6  A: 

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!

Jonathan Sampson
+1  A: 

Sorry about not giving you detailed explanation, but maybe you could take a look at DokuWiki for a starting point.

In its setup it accepts 3 modes:

  1. Regular urls: ?id=zzz
  2. .htaccess rewrite: uses apache to do the rewritting
  3. internal (php) rewrite: urls end up looking like http://www.example.com/kb/doku.php/start

It's free so you can just download and browse the code.

As a note, the apache redirect is very likely the best solution but the pure php one is also interesting in case your code is going to run in IIS6 servers where rewritting is not as easy as in apache.

Carlos Lima
+1  A: 

Unfortunately, it's really up to the web server, not PHP. Depending on if you use Apache or something else, it has to do this before your script is executed. I use mod_rewrite, and an example rewrite rule looks like this:

<Directory "/home/www/html">
    RewriteEngine On
    RewriteBase /
        RewriteCond %{REQUEST_FILENAME} !-f
        RewriteCond %{REQUEST_FILENAME} !-d
        RewriteRule ^(.*)$ /index.php/%{REQUEST_URI} [PT,L]
</Directory>

The above rule basically says if the URL is a valid path to a real file or directory, load it. Otherwise, run it through index.php.

Poldon
+2  A: 

If your server supports it (apache / mod_rewrite), you can use a .htaccess file to re-direct the visitor.

Something like (just a draft, adapt to your own needs...):

RewriteEngine On
RewriteRule ^([a-zA-Z]+)/([a-zA-Z]+)/([0-9]+)/([-0-9a-zA-Z]+)/?$ /$1/$2.php?id=$3 [L]

for the second example.

jeroen
A: 

I think this was asked before. Look here my complete solution for this.

Gabriel Sosa
+2  A: 

Using mod rewrite:

RewriteRule ^videos/play/([0-9]+)/([^.]+)$ play.php?id=$1&name=$2

example.com/play.php?id=203&name=google-io-2009-wave-intro

would work as

example.com/videos/play/203/google-io-2009-wave-intro

Paul Janaway
+1  A: 

Keep in mind that redirecting is not the same as rewriting.

A redirect is when the server receives the request and the response is sent as a redirect. For instance, you request a page www.example.com/page. When the server receives this, either the page or the server self issues a redirect command to the browser. The redirect command basically says "go here: new page". In PHP, this is in the form of header('Location: newpage.html');

A rewrite is when the server receives the request from the browser then looks in a list of matching regular expressions for that site. If a match is found, the URL is rewritten into that form and is responded to accordingly. For instance, the requested URL www.example.com/specificpage could be rewritten (on the server end) as www.example.com/?loadpage=specificpage. The browser never receives header information stating that it must go somewhere else.

Andrew Sledge
+1  A: 

You could approach this slightly differently from the suggestions above by using a Front Controller, it's a common solution for making custom URLs and is used in all languages, not just PHP. Here's a guide: http://www.oreillynet.com/pub/a/php/2004/07/08/front%5Fcontroller.html

Essentially you would create an index.php file that is called for every URL, its job is to parse the URL and determine which code to run based on the URL's contents. So, for example a user would use a URL such as http://example.com/index.php/videos/play/203/google-io-2009-wave-intro and index.php would extract the remaining elements from the URL (/videos/play/203/google-io-2009-wave-intro) take the first part, load a php file with that name (videos.php or you can make it use play.php) and pass through the parameters 203 and google-io.

It's effectively doing the same thing as rewriting the code in mod_rewrite but does have a few benefits:

  1. Doesn't require too much mod_rewrite code if you are new to that.
  2. Allows you to put all security code in one place - in index.php
  3. It's easy to change URLs and handle 404s etc.

You can remove index.php from the URL using mod_rewrite, see here: http://www.wil-linssen.com/expressionengine-removing-indexphp/

Steve Claridge
+1  A: 

Here is a good tutorial from Nettuts on mod_rewrite.

Xaisoft