重写根目录 Apache 中用户名的 URL 字符串



目前我有以下.htaccess文件:

RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME}% !-d
RewriteCond %{REQUEST_FILENAME}% !-f
RewriteRule .(js|css)$ - [L]
RewriteRule ^/?u/(.*?)/?$ /user-profile?user_id=$1 [L]
RewriteRule ^(.+)$ index.php [QSA,L] 

它将所有文件和目录重写为index.php,这会进一步路由,忽略静态 js/css 文件。

有了这一行:

RewriteRule ^/?u/(.*?)/?$ /user-profile?user_id=$1 [L]

我正在将所有请求重定向到类似website.com/user-profile?user_id=timmwebsite.com/u/timm.我试图弄清楚如何使其重定向到简单的website.com/timm,但到目前为止我尝试的所有方法都给了我 500 错误。

这是我最终采用的解决方案,如果有人发现自己处于类似的情况。它可能与其他任何人的用例不匹配,但您永远不知道。

RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME}%  !-d
RewriteCond %{REQUEST_FILENAME}%  !-f
RewriteRule .(js|css)$           -                            [L]
RewriteRule ^/?edit-list/(.*?)/?$ /edit-list?list_id=$1        [L]
RewriteRule ^(.*)$                index.php?username-router=$1 [QSA,L]

我的整个路由器看起来像这样:

// Routing
$redirect = $_SERVER['REDIRECT_URL'];
$method = $_SERVER['REQUEST_METHOD'];
// Get the path after the hostname
$path = ltrim($redirect, '/');
// Check if path matches a user
$username = $userControl->getUserByUsername(ltrim($path));
// Get controller name by converting URL of dashes
// (such as forgot-password) to uppercase class names
// (such as ForgotPassword) and assign to the proper
// controller based on URL.
$controllerName = getControllerName($redirect);
$controllerPath = $root . "/src/controllers/{$controllerName}.php";
// Load index page first
if ($controllerName === '') {
$controller = new Index($session, $userControl);
}
// If the controller exists, route to the proper controlller 
elseif (file_exists($controllerPath)) { // to do: add approved filenames
$controller = new $controllerName($session, $userControl);
}
// If path matches user in the database, route to the public
// user profile.
elseif ($username) {
$controller = new UserProfile($session, $userControl);
} 
// If all else fails, 404.
else {
$controller = new ExceptionNotFound($session, $userControl);
}
// Detect if method is GET or POST and route accordingly.
if ($method === 'POST') {
$controller->post();
} else {
$controller->get();
}

最新更新