Search code examples
phpapache.htaccessmod-rewrite

.htaccess rewrite root to get action


I have the following code, its purpose is to direct the user to different functions depending on the action specified in a URL.

$action = isset( $_GET['action'] ) ? $_GET['action'] : "";

$action = strtolower($action);

switch ($action) {
  case 'viewproducts':
    viewProducts();
    break;
  case 'products':
    products();
    break;
  case 'homepage':
    homepage();
    break;
  default:
        header("HTTP/1.0 404 Not Found");
        include_once("404.html");
}

I would like to direct the user to homepage if they are on the index or /.

RewriteEngine On
#if not a directory listed above, rewrite the request to ?action=
RewriteCond %{REQUEST_FILENAME} !-f 
RewriteCond %{REQUEST_FILENAME} !-d

RewriteRule ^/$ index.php?action=homepage [L,QSA]
#RewriteRule ^(.*)$ index.php?action=$1 [L,QSA]

However when on domain.com/ the switch defaults.


Solution

  • Well, it's not the .htaccess issue. It's your code. I would use this .htaccess:

    RewriteEngine On
    RewriteBase /
    
    ## If the request is for a valid directory
    RewriteCond %{REQUEST_FILENAME} -d [OR]
    ## If the request is for a valid file
    RewriteCond %{REQUEST_FILENAME} -f [OR]
    ## If the request is for a valid link
    RewriteCond %{REQUEST_FILENAME} -l
    ## don't do anything
    RewriteRule ^ - [L]
    
    RewriteRule ^(.*)$ index.php [L]
    

    So all request just go straight to index.php, and in your "router" should be:

    $action = isset( $_GET['action'] ) ? $_GET['action'] : "homepage";
    

    Because you setting $action to empty string if it's not specified, so switch defaults.

    P.S.: Just an advice. Do not build your own CMS, use frame or whatever. It's best to concentrate on your product than on development tools.

    UPDATE

    As OP suggested, RewriteRule can be:

    RewriteRule ^(.*)$ index.php?action=$1 [L,QSA]
    

    Hovewer, in my example .htaccess is from HTML5 Boilerplate, so it's tested and suitable for most cases (works for me as well).