使用mod_rewrite更改URL

时间:2012-08-28 01:39:43

标签: php .htaccess mod-rewrite url-rewriting

当访问者访问我的网站,并输入以下格式的网址myWebsiteName / userName时,会将其转发到脚本,该脚本会查找与userName关联的成员ID,然后转发到个人资料页面。

问题是url更改为myWebsite / member-profile?member_id形式但我希望它保留在输入到url中。我相信这与mod_rewrite有关,但不知道适用哪些条件或规则。

下面是我的.htaccess文件和查找成员个人资料的脚本代码。有什么建议吗?

SuPHP_ConfigPath /home/helcupor/public_html
RewriteEngine On
RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]

#for files, append .php
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.*)$ $1.php

#for vanity urls redirect to url2id.php
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^\.]+)$ url2id.php?vanityName=$1 [L]

AuthUserFile "/home/helcupor/.htpasswds/public_html/passwd"

ErrorDocument 404 /routing.php
#AuthName "/admin/"

url2id.php

<?php
include("includes/functions-and-vars.inc");
$connection = mysql_connect('localhost','','');
$vanityName = explode("/",$_SERVER['REQUEST_URI']);

if(strlen($vanityName['1'])>0)  {
    $vanityName = mysql_real_escape_string($vanityName['1'],$connection);
    $validSpecialChars = array('-', '_'); 
    if(ctype_alnum(str_replace($validSpecialChars, '', $vanityName)))   {
        $user = db_connect("SELECT mem_id FROM users WHERE vanity_url = '$vanityName' LIMIT 1");
        if(mysql_num_rows($user)==1)    {
            $newArray = mysql_fetch_array($user);
            $memID = $newArray['mem_id'];
            header('location:member-profile.php?mem_id='.$memID.'&token=1');
            exit;
        }
        else {
            header('location:advanced-search.php?error=user_not_found');
            exit;
        }
    }
    else    {
        header('location:advanced-search.php?error=user_not_found');
        exit;
    }
}
else    {
    header('location:index.php');
    exit;
}

    //echo '<br>' . $vanityName;

?>

1 个答案:

答案 0 :(得分:0)

将此用于.ttaccess文件。

RewriteRule ^([a-zA-Z0-9_-]+)$ member_profile.php?member_id=$1

创建member_profile.php并以username而非userid的形式获取member_id。现在使用用户名进行用户标识转换并验证您的用户名。并显示特定用户名的个人资料。