How to do URL re-writing in PHP?

前端 未结 9 2058
死守一世寂寞
死守一世寂寞 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:13

    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_controller.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/

    0 讨论(0)
  • 2020-11-22 15:15

    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.

    0 讨论(0)
  • 2020-11-22 15:16

    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.

    0 讨论(0)
提交回复
热议问题