How to do URL re-writing in PHP?

前端 未结 9 2206
死守一世寂寞
死守一世寂寞 2020-11-22 14:38

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 and MySQL?

In my applic

9条回答
  •  执笔经年
    2020-11-22 15:00

    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!

提交回复
热议问题