• Blogs (9)
    • 📱 236 - 992 - 3846

      đź“§ jxjwilliam@gmail.com

    • Version: ‍🚀 1.1.0
  • web server .htaccess

    Blogs20142014-03-11


    Web Server .htaccess routing example

    For a PHP micro-framework and quick solution, using web-server’s (like Apache) URL rewrite(mod_rewrite) is a good choice. Just add/edit .htaccess file in specific/various dirs to control the URL routines. A standard .htaccess file:

    RewriteEngine On
    RewriteBase /name/
    
    RewriteCond %{DOCUMENT_ROOT}/name/$1.php -f
    RewriteRule ^([^/]+)/([^/]+)/?$ $.php1?action=$2 [L,NC,QSA]
    
    RewriteCond %{DOCUMENT_ROOT}/name/$1.php -f
    RewriteRule ^([^/]+)/([^/]+)/([^/]+)/?$ $1.php?action=$2&id=$3 [L,NC,QSA]
    
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME}.php -f
    RewriteRule ^(.*)$ $1.php [L]

    This will convert a php HTTP request to a better meaningful URL:

    //From HTTP Request:
    routing.php
    routing.php?action=create
    routing.php?action=list&id=1
    
    // To:
    /routing
    /routing/create
    /routing/list/1

    In this way, PHP doesn’t involve into routing request. Compared to PHP MVC framework and routine, it is faster, but less extensible and flexibility. A good URL rewriting example from CakePHP is at:

    http://book.cakephp.org/2.0/en/installation/url-rewriting.html