【问题标题】:How to set htaccess to get parameters from user friendly URL to use with JS如何设置 htaccess 以从用户友好的 URL 获取参数以与 JS 一起使用
【发布时间】:2019-04-09 05:42:58
【问题描述】:

我希望用户看到这个漂亮的 URL:

www.example.com/michael

我的代码能够通过 GET 将其作为变量获取:

www.example.com?user=michael

JavaScript 方面,我正在测试它:

var userId = getQueryString('user');
console.log("user="+userId);

.htaccess 方面我正在使用这个:

RewriteEngine On
RewriteRule ^([^/]*)$ ?user=$1 [L]

当我加载“www.example.com/michael”时,我没有重定向到 404,这很好。但是控制台输出“user=null”。它不通过 GET 获取参数。我做错了什么?

【问题讨论】:

    标签: javascript .htaccess url friendly-url


    【解决方案1】:

    在您的.htaccess 中,编写以下代码:

    RewriteEngine On
    RewriteRule ^([A-Za-z0-9])/?$ /index.php?user=$1 [NC,L]
    

    因此您可以输入www.example.com/michaelwww.example.com/michael/ 甚至www.example.com/MICHAEL 访问您的网站

    如果要在 JavaScript 中获取user 参数,请使用以下代码:

    const urlParams = new URLSearchParams(window.location.search);
    const username = urlParams.get('user');
    

    但是请记住,如果您使用Rewrite 模式,JavaScript 不会检测参数user,因为从浏览器的角度来看,URL 是“/michael”而不是“/?user=michael” . JavaScript 只查找友好路径。

    您可以改用重定向,因此当有人访问键入“/michael”时,您会将用户重定向到“/?user=michael”。

    编辑:另一种解决方案是解析整个 URL,捕获 URL www.example.com/michael 的第一个“/”块。例如:

    var username = location.href.substring(location.protocol.length).substr(2).substring(location.href.substring(location.protocol.length).substr(2).indexOf('/') + 1);
    

    希望对你有帮助!

    【讨论】:

    • 对不起,不,它没有。我没有 index.php,也没有使用 PHP。我在根目录中有一个 index.html。另外,我不应该收到 404 错误。
    • @HarunAlikadić 这只是一个例子!只需将 index.php 替换为 index.html 或其他任何东西!看看我的编辑评论。
    • @HarunAlikadić JavaScript 永远不会看到 /index.html?user=michael,因为 Rewrite 它不适合与 JS 一起使用。 JavaScript 只查找 window.location.href,在这种情况下它是 www.example.com/michael,它将是 JavaScript 可以解析的内容。
    • 我知道最好的解决方案可能是使用重定向,因此当有人访问键入“/michael”时,我会将用户重定向到“/?user=michael”。但是此时,使用您的 htaccess 脚本,当我访问“/michael”时,我收到 404 错误。为什么?
    • @HarunAlikadić 试试RewriteRule /^([A-Za-z0-9])/?$ /index.html?user=$1 [NC,L] 看看/^
    猜你喜欢
    • 2011-12-17
    • 2012-04-25
    • 2011-10-16
    • 2011-07-11
    • 2015-07-24
    • 1970-01-01
    • 2022-11-29
    • 2020-12-25
    • 1970-01-01
    相关资源
    最近更新 更多