RewriteRule: redirect to index.php when not matching

Discussion in 'Apache' started by Cequiel, Jan 24, 2012.

  1. #1
    Hi Everyone,
    What I want to do is quite simple, but I don't know how to achieve it. And I have spend too many hours thinking about it.

    This's the problem. My .htaccess file is as follows:

    Options +FollowSymlinks
    RewriteEngine on
    RewriteRule ^.*login/?$ login.php
    RewriteRule ^.*comment/?$ comment.php
    RewriteRule ^.*blah/?$ blah.php

    This allows me to redirect to the appropiate php file. For example, when the user enters the following url:
    mycustomdomain.com/section1/section2/section3/../login

    Apache redirects to the login.php file, no matter "section1/section2/section3/.." is.

    What I want to do is redirect to index.php when my request doesn't match any of the above rules. For example, when the user enters the following url:

    mycustomdomain.com/section1/section2/section3/../tralariquetevi

    I would like to redirect the request to index.php, because "tralariquetevi" is not listed in the above rules.

    How could I achieve that?
    Thank you very much.
     
    Cequiel, Jan 24, 2012 IP
  2. Cequiel

    Cequiel Peon

    Messages:
    5
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #2
    This is what I did, just in case someone has the same problem as me:

    .haccess file:
    --------------
    # Rewrite mapping rules
    RewriteRule ^(([^/]+/)*)login/$ login.php?path=$1 [L]
    RewriteRule ^(([^/]+/)*)comment/$ comment.php?path=$1 [L]
    RewriteRule ^(([^/]+/)*)page1/$ page1.php?path=$1 [L]
    RewriteRule ^(([^/]+/)*)page2/$ page2.php?path=$1 [L]
    RewriteRule ^(([^/]+/)*)page3/$ page3.php?path=$1 [L]
    
    # Rewrite all requests to index.php
    # except directories and files
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule . index.php [L]
    Code (markup):
    index.php file:
    ---------------
    /* 
     * If '/' is missing at the end of the url request and it has no parameters, 
     * add it and redirect. 
     */ 
    $info = parse_url($_SERVER["REQUEST_URI"]); 
    $path = $info["path"]; 
    if (!array_key_exists("query", $info) && !preg_match("#/$#", $info["path"])) { 
            header("Location: $path/"); 
            die(); 
    }
    // rest of code...
    PHP:
    page.php file:
    --------------
    /* 
     * If the request is not a valid url, print a 404 error 
     */ 
    $path = array_key_exists("path", $_REQUEST)? $_REQUEST["path"]: NULL; 
    if (!is_valid_path($path)) { 
            header('HTTP/1.0 404 Not Found'); 
            echo file_get_contents("templates/page_not_found.html"); 
            die(); 
    }
    PHP:
     
    Cequiel, Jan 24, 2012 IP