How to implement URL Routing in PHP.
-
Possible duplicate: http://stackoverflow.com/questions/125677/php-application-url-routing. Try looking at that question. – Macha Aug 22 '09 at 14:03
-
In fact, possible triplicate =) – Zed Aug 22 '09 at 14:11
-
Either they're working together or it's a sock puppet account. – random Aug 22 '09 at 14:22
-
watch this tutorial https://www.youtube.com/watch?v=byjMGftJeyU – jasinth premkumar Feb 20 '18 at 16:31
2 Answers
If you use Apache you can do the URL routing via mod_rewrite.
Small example:
RewriteEngine On
RewriteRule ^(dir1)/?(path2)? main.php?dir=$1&path=$2
That'll have any request like
http://yoursite.com/dir1/path1
served by
http://yoursite.com/main.php?dir=dir1&path=path2
More examples here.
The other alternative have every request redirect to a single php file
RewriteEngine On
RewriteRule (.*) main.php?request=$1
and then to do it in code, where you can use a similar approach, by having a set of regular expressions that are matched by some code and then redirected via header() or just internally.

- 1
- 1

- 330,807
- 53
- 334
- 373
First of all, you will need Apache's (I suppose your webserver is Apache) mod_rewrite
to be enabled.
Then, you need to create a RewriteRule to redirect everything to your index.php page.
Something like this could do :
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule .* index.php
It will redirect every request to a file that doesn't exist to index.php ; this means that, if the requested URL is www.example.com/blah, it is actually index.php that will be called.
About that, here a couple of link that can help :
Then, this page has to determine what has to be displayed, depending on what initial URL was called -- or what parameters are received.
This can be done using the Design Pattern Front Controller, for instance -- it's implemented in most modern PHP Frameworks, for instance.
There have been many questions of this subject on SO ; some of those (and their answers) might probably help you. For instance :

- 1
- 1

- 395,085
- 80
- 655
- 663
-
This should be the standard answer to this question. It works for any server-side language running on Apache, and piles of rewrite rules are not particularly sustainable anyway. – Isabelle Wedin Jan 19 '14 at 20:24