用用户名重写配置文件URL


Rewrite profile URL with username

在这段使用mod_rewrite的代码中,我可以通过在域后键入任何用户的用户名来访问他的配置文件,如example.com/john,这将带我们访问john的配置文件。然而,如果我在数据库中键入任何不是现有用户用户名的名称(如example.com/notauser),我仍然会被重定向到一个空的个人资料页面,尽管它没有个人资料图片或其他信息,但所有其他按钮和链接(如关注者、朋友等)仍然可用。在这种情况下,我想重定向到登录页面或echo消息用户不存在,但不知道如何做到这一点。

Profile.php

<?php
if(!empty($_GET['username'])) { 
$username = $_GET['username'];
}
else if(!empty($_SESSION['username'])) { 
$username = $_SESSION['username'];
}
else { 
header("Location: login.php"); 
die();
}
?>

.htaccess

RewriteEngine On
RewriteRule ^([a-zA-Z0-9_-]+)$ profile.php?username=$1 

我想重定向到登录页面,否则echo消息用户没有存在,但不知道如何做到这一点。

由于动作取决于用户不存在的因素;您需要在尝试为所提供的$username获取数据后执行重定向。