【问题标题】:mod_rewrite to remove .html from address bar without changing links in the html filemod_rewrite 从地址栏中删除 .html 而不更改 html 文件中的链接
【发布时间】:2019-07-31 11:05:12
【问题描述】:

第一个问题。所以我在 Apache 上有一个简单的网站“website.com”:

website.com
    index.html
    site1.html
    site2.html

在每个 html 中,我都有指向其他的链接,格式如下:

<a href="index.html">main</a>
<a href="site1.html">site1</a>
<a href="site2.html">site2</a>

我希望浏览器显示“website.com/site1”而不是“website.com/site1.html”。

我已经玩了几天了,我总是得到以下结果之一:

  1. 无限循环的重定向。
  2. 内部服务器错误。
  3. 两个版本都有效(例如“website.com/site1.html”和“website.com/site1”),但 .html 保留在地址栏中。

我不知道发生了什么。我什至无法正确打破它。例如,我预计这个 .htaccess 会在访问“website.com/site1”时抛出错误,因为没有规则将 site1 重定向到 site1.html:

RewriteEngine on

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

RewriteRule ^(.*)\.html$ /$1 [R=302,QSA]

但不行 - 它有效,只是不会删除地址栏中的 .html。

Apache 如何知道在没有适当的 RewriteRule 的情况下将“website.com/site1”重定向到“website.com/site1.html”?我的理解是否错误,我必须从 website.com/site1 重定向到 website.com/site1.html 才能使其正常工作?

提前致谢。

【问题讨论】:

    标签: html apache .htaccess mod-rewrite


    【解决方案1】:

    规则的最后一行:

    RewriteRule ^(.*)\.html$ /$1 [R=302,QSA]
    

    这意味着仅将任何file.html 更改为file,您需要将file 仅在内部重定向到file.html,如下所示:

    RewriteRule ^(.*)$ /$1.html [L,QSA]
    

    但是,在这种情况下,file.html 将保持原样,如果您想完全删除 .html,请尝试以下规则:

    RewriteEngine on 
    RewriteCond %{THE_REQUEST} \s/+(.*)\.html[\s?/] [NC]
    RewriteRule ^  /%1 [R=301,L,NE]
    
    RewriteCond %{REQUEST_FILENAME}   !-f 
    RewriteCond %{REQUEST_FILENAME}\.html -f
    RewriteRule ^(.*)$ /$1.html [L]
    

    RewriteEngine on 之后的前两行将删除 .html

    其余行将检查没有扩展名的请求是否为.html文件,如果它被接受.html,它将被重定向但在内部。

    现在,site1.htmlsite1 在浏览器中都将是 site1

    这样,您将确保文件在重定向之前接受.html 扩展,并且将与错误文件混合的这一阶段分开。

    【讨论】:

    • 像魅力一样工作,谢谢,接受。请问为什么第一个RewriteCond里面有“\s”?我不希望 url 中有空格字符。
    • 你能告诉我你运行的是什么版本的apache吗?我正在运行 apache 2.4.18,但此代码无法按预期工作。此代码出错并查找“/file”名称而不是“file”并将 example.com/project.html 更改为 example.com//project。 mybe,您是为较新的 apache 版本设计的吗?谢谢。
    猜你喜欢
    • 2013-09-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-10
    • 1970-01-01
    • 2014-09-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多