简体   繁体   English

.htaccess 用 GET 变量重写

[英].htaccess rewrite with GET variables

am trying to create a url like this using.htaccess... www.example.com/user/david我正在尝试使用 .htaccess 创建这样的 url ... www.example.com/user/david

what i have now is this www.example.com/user?username=david我现在拥有的是这个www.example.com/user?username=david

It works well when i do something like当我做类似的事情时效果很好

RewriteEngine on

RewriteCond %{REQUEST_FILENAME} !-f

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

But i am wrong at my php code.但是我的 php 代码错了。

if(isset($_GET["username"]))
{
    $stmt = $mysqli->prepare("SELECT * FROM campus_users WHERE campus_name = ?");
    $stmt->bind_param("s", $campus_name );
    $campus_name = trim($_GET["username"]);
    $stmt->execute();
    $result = $stmt->get_result();

    if ($result->num_rows == 1) {
        $row = $result->fetch_array(MYSQLI_ASSOC);
        //displaying users rows
    } else {
        header("location: blank-page");
      exit();
    }
} else {
  header("location: home.php");
  exit();
}

But when i enter the url like this www.example.com/user?username=david it works well...但是当我像这样输入 url www.example.com/user?username=david时,它运行良好......

The problem is i want a smart looking url which isnt working due to my php i guess.问题是我想要一个看起来很漂亮的 url,我猜是因为我的 php 而无法正常工作。

Please help me.请帮我。 Thanks in advance.提前致谢。

If your URL with query string is working fine then it most probably it means your .htaccess rules are not working, usually we give user friendly URLs to users in your case it should be www.example.com/user/david and internally it should route to www.example.com/user.php?username=david .如果您的带有查询字符串的 URL 工作正常,那么这很可能意味着您的.htaccess规则不起作用,通常我们会为用户提供用户友好的 URL,在您的情况下它应该是www.example.com/user/david并且在内部它应该路由到www.example.com/user.php?username=david Please try following Rules in your .htaccess file.请尝试遵循.htaccess文件中的规则。

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} ^/user/(.*)$
RewriteRule ^.*$ /user.php?username=%1 [QSA,NC,NE,L]

NOTE: if possible and you are not on prod systems then you could try to restart your Apache service too, though it's not necessary but sometimes it may be required.注意:如果可能并且您不在生产系统上,那么您也可以尝试重新启动 Apache 服务,虽然这不是必需的,但有时可能需要。 Also use user friendly URL as mentioned above in browser make sure you clear the browser cache before hitting it.也可以使用上面提到的用户友好的 URL 在浏览器中确保在点击它之前清除浏览器缓存。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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