【问题标题】:Rewrite URL string for username in root directory Apache重写根目录 Apache 中用户名的 URL 字符串
【发布时间】:2018-06-22 21:47:48
【问题描述】:

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

【问题讨论】:

  • "用这一行...我正在重定向..." - 不,你从左到右重写,而不是反过来。
  • @smith 如果我删除该行,我将无法再使用静态资源。
  • @Jeff 你有解决办法吗?
  • RewriteRule ^(timm)?$ /user-profile?user_id=$1 [L] 应该可以解决问题(但我现在无法测试)
  • 如果你只是想要一个重写规则将website.com/u/timm重定向到website.com/timm,试试RewriteRule ^\/u\/(\w+)$ /$1

标签: php apache .htaccess url-rewriting routing


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-02-13
    • 2014-06-23
    • 1970-01-01
    • 2014-05-29
    • 1970-01-01
    • 1970-01-01
    • 2021-01-06
    • 1970-01-01
    相关资源
    最近更新 更多