开发者

Pull data in database based on url (aka DIGG)

I'm having a hard time even figuring o开发者_高级运维ut how to write a Google search to figure this out.

If you click on a story on Digg it puts it all in the URL like digg.com/news/science/why_the_world_is_tilted, instead of digg.com/reader.php?r=news&s=science&t=why_the_world_is_tilted

I'm pretty sure they don't have several million subfolders, and I recall reading something 4 years ago that explained how it works, but I don't remember enough to look it up again.


If you are using Apache, you can accomplish this using mod_rewrite. I'm not an expert on the subject but if you search around for some mod_rewrite tutorials you can find examples where a nice pretty URL is effectively converted into a different query string invisibly on the web server.


There are two basic approaches to this:

  1. Have the web server parse the URL for the data bits you want and convert them to a query string; this is usually done with mod_rewrite
  2. Get the URI from the environment and extract the bits you want yourself. Most good web frameworks will provide a way to do this for you.

For example, in Catalyst you could write:

package My::Application::Controller::News;
# …
# :Path without an argument means the root for the controller. 
# The controller is news so: /news/
# :Args(2) means with two arguments
sub article :Path :Args(2) {
    my ( $self, $c, $category, $article_name ) = @_;
    # …
}

And $category would be populated with "science" and$article_namewith"why_the_world_is_tilted"`


If your server is running Apache and mod_rewrite is installed you can create a file called .htaccess containing this:

<IfModule mod_rewrite.c>
  RewriteEngine on
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteRule ^(.*)$ index.php?q=$1 [L,QSA]
</IfModule>

This will send the path to a request index.php in the var $_GET['q']. It wont send the path to index.php if the path is to an existing file or directory.


What you are talking about is clean url's. This pattern is often used in an MVC architecture.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜