【问题标题】:How do I configure routing in Apache? [closed]如何在 Apache 中配置路由? [关闭]
【发布时间】:2016-10-04 10:42:57
【问题描述】:

如何隐藏我的 .html 文件,例如,当我转到 www.mysite.com 时,它会重定向到 www.mysite.com/index.html 但它隐藏了 /\index.html,因此它保持为 www.mysite .com 但实际上是 www.mysite.com/index.html 。 我真的不知道如何解释,但如果你能理解我,请帮忙,谢谢。

【问题讨论】:

  • 您想从所有 URL 中删除 .html。假设联系我们页面应该是 www.mysite.com/contact 而不是 www.mysite.com/contact.html?
  • 这不是真正的 javascript 问题。专注于 apache 的 URL 重写。
  • @RahulPatel 是的,没错,我该怎么做?
  • Apache 自动将所有请求转发到//index.html。为什么要明确 URL?

标签: html apache routing


【解决方案1】:

.htaccess 文件是您使用记事本或 TextMate 等文本编辑器创建的简单 ASCII 文件。它提供了一种基于每个目录进行配置更改的方法。

RewriteRule ^([^\.]+)$ $1.html [NC,L]

来源 - How to remove .php, .html, .htm extensions with .htaccess

【讨论】:

  • 感谢您的帮助:)
【解决方案2】:

请在您的 .htaccess 文件中写入以下代码。

RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_URI} \.html$
RewriteRule ^(.*)\.html$ $1 [R=301,L]

.html 将使用上述代码从您的 URL 中删除。 假设您的联系我们页面 URL 是 www.mysite.com/contact.html,因此使用上面的代码将改为 www.mysite.com/contact

【讨论】:

  • 非常感谢,非常感谢您的帮助 :)
  • 很高兴能帮到你。 (y)
【解决方案3】:

试试这个,这里我们设置目录索引,所以我们不必在每次调用中都提到 index.html。并重写每个没有扩展名的html。

DirectoryIndex index.html

RewriteEngine on
RewriteCond %{REQUEST_FILENAME}.html -f
RewriteRule ^([\w-]+)$ $1.html [L]

【讨论】:

    【解决方案4】:

    如果您要求仅在索引页面中编辑客户端的 URL 文本。您可以通过 JavaScript 将 HTML 文件中的路径名替换为 this answer 中的代码:

    history.replaceState('data to be passed', 'Title of the page', 'theNameWithoutTheHTML');
    

    应该为每个页面的每个.js更改名称,或者您可以使用更通用的脚本并重复使用它:

    history.replaceState('data to be passed', 'Title of the page', location.pathname.slice(0, -5)); //This will replace it with the same path, removing the ".html" at the end (take care if the extension is different sized)
    

    在这种情况下,您正在重定向到 .html 文件,当用户重新加载页面时应该没有任何问题(因为它会尝试在没有 .html 的情况下加载页面)。

    【讨论】:

      【解决方案5】:

      此方法不使用apache。它只是重构代码。

      您也可以尝试使用为路由创建不同的目录。 例如对于联系人页面,您将在项目的根目录中有一个文件夹名称联系人。在该文件夹中,将contact.html 作为index.html 放置。 这种重组可以帮助您根据路由拆分代码。

      联系页面的链接为 www.mysite.com/contact(浏览器为 www.mysite.com/contact/index.html)。

      【讨论】:

        猜你喜欢
        • 2022-12-29
        • 2012-08-28
        • 2021-06-03
        • 2016-06-08
        • 1970-01-01
        • 2012-10-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多