首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在根目录Apache中重写用户名的URL字符串

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

Stack Overflow用户
提问于 2018-06-21 20:56:33
回答 1查看 45关注 0票数 0

目前,我有以下.htaccess文件:

代码语言:javascript
复制
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文件。

用这一行:

代码语言:javascript
复制
RewriteRule ^/?u/(.*?)/?$ /user-profile?user_id=$1 [L]

我将所有请求重定向到类似于website.com/user-profile?user_id=timm的东西到website.com/u/timm。我试图弄清楚如何将它重定向到简单的website.com/timm,但是到目前为止,我所尝试的一切都给了我一个500个错误。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-06-22 13:47:48

如果有人发现自己处于类似的情况下,下面就是我最后提出的解决方案。它可能与其他人的用例不匹配,但你永远不会知道。

代码语言:javascript
复制
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]

我的整个路由器都是这样的:

代码语言:javascript
复制
// 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();
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50977313

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档