User friendly URLs - mod rewrite and php redirections

前端 未结 4 614
我在风中等你
我在风中等你 2021-01-18 13:18

So far I\'ve done this:

RewriteBase /
RewriteCond  %{REQUEST_FILENAME} !-f
RewriteCond  %{REQUEST_FILENAME} !-d
RewriteRule  ^(.*)$ index.php?load=$1 [QSA,L]         


        
4条回答
  •  花落未央
    2021-01-18 14:02

    Here is simple example to begin with:

    .htaccess

    RewriteEngine On
    RewriteRule ^includes/.*$ index.php
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^(.*)$ index.php [QSA,L]
    

    First, you must deny direct access to .php files, you can put them in separate folder like '/includes' and redirect any call to that folder to index.php. Second, allow direct access to files ( like images or javascripts ). Last rule, redirect anything else to index.php.

    PHP

    Basically you must have set of rules to test URL and some controller to handle the result.

    define( 'WEB_ROOT', rtrim( dirname($_SERVER["SCRIPT_NAME"]), '/' ) );
    define( 'INCLUDES_ROOT', 'includes/' );
    
    // examples of rewrite rules ( $key = action, $value = regular expression )
    $rules = array( 
        'pages' => "/(?'page'dashboard|about|signin|signup)",   // e.g. '/about'
        'gallery' => "/(?'username'[\w\-]+)/gallery",   // e.g. '/some-user/gallery'
        'album' => "/(?'username'[\w\-]+)/(?'album'[\w\-]+)",   // e.g. '/some-user/some-album'
        'picture' => "/(?'username'[\w\-]+)/(?'album'[\w\-]+)/(?'picture'[\w\-]+)",     // e.g. '/some-user/some-album/some-picture'
        'home' => "/"   // e.g. '/'
        );
    
    // get uri
    $uri = '/' . trim( str_replace( WEB_ROOT, '', $_SERVER['REQUEST_URI'] ), '/' );
    
    // test uri
    foreach ( $rules as $action => $rule ) {
        $pattern = '/^'.str_replace( '/', '\/', $rule ).'$/';
    
        if ( preg_match( $pattern, $uri, $params ) ) {
            /* now you know the action and parameters so you can 
             * include appropriate template file ( or proceed in some other way )
             * NOTE: variable $params vill be visible in template ( use print_r( $params ) to see result )
             */
            include( INCLUDES_ROOT . $action . '.php' );
            // exit to avoid the 404 message 
            exit();
        }
    }
    
    // nothing is found so handle 404 error
    include( INCLUDES_ROOT . '404.php' );
    

    The next step is to check the received parameters.

提交回复
热议问题