mod_rewrite $_GET

前端 未结 2 855
醉梦人生
醉梦人生 2021-01-27 03:47

I have a FrontController expecting two $_GET params:

controller
action

A typical call to the site would look like thi

相关标签:
2条回答
  • 2021-01-27 04:19

    The .htaccess you posted works for me:

    // GET /cont1/action1
    
    print_r($_GET);
    
    /* output
    Array
    (
        [controller] => cont1
        [action] => action1
    )
    */
    

    You might want to try an absolute path to index.php rather than a relative one.

    Regardless, that regex will result in:

    // GET /cont1/action1/arg1
    
    print_r($_GET);
    
    /* output
    Array
    (
        [controller] => cont1/action1
        [action] => arg1
    )
    */
    

    You'd be better off doing:

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

    And having your index.php split up the $_GET['url'] into controller, action, args, etc...

    0 讨论(0)
  • 2021-01-27 04:26

    There are 2 parts to getting this working. If you are working with PHP and Apache, rewrite engine must be available on your server.

    In your user folder put a file named .htaccess with these contents:

     RewriteEngine on
     RewriteCond %{REQUEST_FILENAME} !-d
     RewriteCond %{REQUEST_FILENAME} !-f
     RewriteRule . index.php [L]
    

    Then your index.php you can use the REQUEST_URI server variable to see what was requested:

    <?php
    $path = ltrim($_SERVER['REQUEST_URI'], '/'); 
    echo $path;
    ?>
    

    If someone requested /start/register, then assuming all the above code is in the html root, the $path variable would contain start/register.

    I'd use the explode function on $path using the / as a separator and pull the first element as register.

    The rewrite code has the benefit of working with filenames and directory names.

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