尝试查看不存在的用户的配置文件时显示404页面

时间:2012-06-07 17:40:25

标签: php .htaccess

在我的网站中,用户个人资料的网址为mysite.com/user/username。我真正想做的那个网址应该是mysite.com/username。 我已经完成了将这些代码行添加到htaccess文件

RewriteRule ^([a-zA-Z0-9_-]+)$ user.php?uname=$1
RewriteRule ^([a-zA-Z0-9_-]+)/$ user.php?uname=$1

现在我可以通过mysite.com/username与用户联系。但错误是,现在404文件不起作用。如果我输入不存在的网址,如myste.com/dasdfsf,它不会获得404文档,因为它查找所有数字和字母(以查找用户名)并给我 我为无效的用户名创建的空白页面。如果该用户不存在,我希望它显示404页面。

2 个答案:

答案 0 :(得分:2)

为什么要显示无效用户名的空白页?请改为显示您的404页面。

答案 1 :(得分:2)

重定向:

RewriteRule ^user/([a-zA-Z0-9_-]+)$ http://example.com/$1 [R=301,L]
RewriteRule ^([a-zA-Z0-9_-]+)$ user.php?uname=$1 [L] #use the L option to stop processing
RewriteRule ^([a-zA-Z0-9_-]+)/$ user.php?uname=$1 [L]

要显示404,您需要设置404页面并向user.php添加逻辑以进行阅读。

<?php
    if(!userExist()){
        header('Status: 404 Not Found');
        echo file_get_contents('404.php');
        exit;//do this if there is code below that assumes this is a valid user
    }
?>
相关问题