我有以下代码,其目的是根据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=$1 [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
,在你的"路由器"中应该是:
$action = isset( $_GET['action'] ) ? $_GET['action'] : "homepage";
因为如果未指定$action
,则将其设置为空字符串,所以切换为默认值。
附言:只是个建议。不要构建自己的CMS
,使用框架或其他任何东西。与其专注于开发工具,不如专注于您的产品
更新
正如OP所建议的,RewriteRule
可以是:
RewriteRule ^(.*)$ index.php?action=$1 [L,QSA]
悬停,在我的示例中,.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=$1 [L,QSA]