简体   繁体   中英

Rewrite URL string for username in root directory Apache

Currently I have the following .htaccess file:

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] 

It rewrites all files and directories to index.php , which does further routing, ignoring static js/css files.

With this line:

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

I am redirecting all requests to something like website.com/user-profile?user_id=timm to website.com/u/timm . I'm trying to figure out how to make it redirect to simply website.com/timm , but everything I have tried so far has given me a 500 error.

Here is the solution I ended up going with, if anyone ever finds themselves in a similar situation. It might not match up to anyone else's use case, but you never know.

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]

My entire router looks like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM