【问题标题】:How to remove or change .html extension in my url using javascript or jQuery? [duplicate]如何使用 javascript 或 jQuery 删除或更改我的 url 中的 .html 扩展名? [复制]
【发布时间】:2014-10-13 09:03:25
【问题描述】:

我的 html 页面网址是 www.example.com/training/product.html。 我想将我的网址更改为 www.example.com/training/product。 strong> 是否可以使用 javascript 或 Jquery?如何?

【问题讨论】:

  • 似乎你应该在服务器端处理一些事情。
  • 您可以尝试更改window.location.href,但更改后可能不起作用,这应该在服务器端。

标签: javascript jquery html


【解决方案1】:

使用javascript,您可以像这样实现:

var newURL = window.location.protocol + "//" + window.location.host + "/" + window.location.pathname;
if (a.indexOf('html') > -1) { //Check of html String in URL.
   url = url.substring(0, newURL.lastIndexOf("."));
}

如果您正在查看服务器级别的更改,以下是 .htaccess 文件的规则

RewriteEngine On

# remove trailing slash
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/]+)/$ http://example.com/folder/$1 [R=301,L]

# Redirect external .html requests to extensionless url
RewriteCond %{THE_REQUEST} ^(.+)\.html([#?][^\ ]*)?\ HTTP/
RewriteRule ^(.+)\.html$ http://example.com/folder/$1 [R=301,L]

# Resolve .html file for extensionless html urls
RewriteRule ^([^/.]+)$ $1.html[L]

【讨论】:

    【解决方案2】:

    您可以通过使用 MVC 来做到这一点。 Javascript 无法做到这一点。这需要在服务器端完成。

    【讨论】:

      【解决方案3】:

      使用 Jquery 试试这个:-

      var url = "www.example.com/training/product.html";
      url = url.substring(0, url.lastIndexOf("."));
      

      【讨论】:

        【解决方案4】:

        抱歉,由于声誉限制,我无法发表评论。

        cmets 中还没有正确的解决方案。

        window.history.replaceState()
        

        完成这项工作。

        我愿意:

        var link = 'www.example.com/training/product.html';
        link.split('.html')[0];
        window.history.replaceState( null, null, link );
        

        如需更受尊重的解决方案,请转至How to reliably get the filename without the suffix in javascript?

        链接:

        https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Manipulating_the_browser_history#The_replaceState().C2.A0method

        【讨论】:

        • 无需对此发表评论,这是正确的答案(甚至带有文档链接),而且现在您距离评论 priv 仅 1 pt。对于浏览器兼容性(IE 主要对此解决方案存在问题),还有一个解决方案使用 URL 末尾的哈希 (#) 来操作文本。
        猜你喜欢
        • 1970-01-01
        • 2011-05-09
        • 2017-12-13
        • 2017-09-26
        • 2011-05-27
        • 2015-03-20
        • 1970-01-01
        • 2015-12-27
        • 2013-04-06
        相关资源
        最近更新 更多