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

时间:2018-06-21 20:56:34

标签: php apache .htaccess url-rewriting routing

当前,我有以下.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错误。

1 个答案:

答案 0 :(得分:0)

如果有人发现自己处于类似情况,这就是我最终要解决的问题。它可能与其他人的用例不符,但您永远不会知道。

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();
}