-4

I have noticed that in Stackoverflow, there are basically 4-6 kinds of different URLs. One is for questions, like http://stackoverflow.com/questions/6831217/double-vs-decimal-in-mysql. One is for user profile page, like http://stackoverflow.com/users/1469954/cupidvogel. One is for new question, like http://stackoverflow.com/questions/ask, etc.

With each page request, the server sends a page as required. Now how do I achieve this on the server side? Should there be one catchall PHP script, which will parse the URL to note what type of page is the client asking (for example, if it parses the URL and finds out that the client is asking for a topic page, it will perhaps extract the question id/text from the URL, query the DB to fetch relevant data, construct the HTTML and send it) and send it accordingly, or should there be separate scripts for each page type? And for either, how do I configure PHP/Apache for this?

If I have a page like foo.php, I can see it through http://localhost/foo.php. But if I want it to capture http://localhost/foo.php as well as http://localhost/foo.php/ask/questions, etc, what do I have to do?

SexyBeast
  • 7,913
  • 28
  • 108
  • 196

1 Answers1

1

See mod_rewrite. This can be accomplished using rewrite rules, which can be place in a .htaccess file or other Apache conf files. As an example:

RewriteRule users/(\d+)/(\w+) user.php?id=$1&uname=$2

This would transform users/1469954/cupidvogel into user.php?id=1469954&uname=cupidvogel. I'd point you toward a tutorial if I knew of a good one (Edit: this one looks decent).

undefined
  • 6,208
  • 3
  • 49
  • 59
  • Yes, I was thinking about Mod_Rewrite as well. Two questions, how do I use it to redirect to the homepage if the pattern doesn't match the list of pre-set patterns, i.e if the user types in some random URL, like `http://stackoverflow.com/foo/users/topics/12345`, obviously this pattern doesn't exist in the list of pre-defined patterns for Mod_Rewrite, so how do I redirect? – SexyBeast Sep 21 '12 at 07:22
  • 1
    I believe you can just put a pattern at the end of all your patterns that matches everything, and point to to index.php or better yet, an error page. Then to prevent your other patterns from also being sent to your default page, add the `[L]` (last) option to the end of your other rules, which tells apache not to process any more rules if that rule matches. – undefined Sep 25 '12 at 00:10
  • That looks promising, will try it out. Thanks. – SexyBeast Sep 25 '12 at 06:28