.htaccess 重写 root 以获取操作

.htaccess rewrite root to get action

我有以下代码,其目的是根据 URL.

中指定的操作将用户引导至不同的 functions
$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");
}

我想将用户引导至 homepage(如果他们在索引中)或 /

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= [L,QSA]

但是当 domain.com/ 开关默认时。

好吧,这不是 .htaccess 的问题。是你的代码。我会用这个 .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]

所以所有请求都直接转到 index.php,在你的 "router" 中应该是:

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

因为你设置 $action 为空字符串,如果没有指定,所以切换默认值。

P.S.: 只是一个建议。不要构建自己的 CMS,使用框架或其他任何东西。最好专注于您的产品而不是开发工具。

更新

正如 OP 所建议的,RewriteRule 可以是:

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

Hovewer,在我的示例中 .htaccess 来自 HTML5 Boilerplate,因此它经过测试并适用于大多数情况(也适用于我)。

您可以使用:

RewriteEngine On
RewriteBase /

RewriteRule ^/?$ index.php?action=homepage [L,QSA]

#if not a directory listed above, rewrite the request to ?action=
RewriteCond %{REQUEST_FILENAME} !-f 
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.+)$ index.php?action= [L,QSA]