【问题标题】:Apache: How can I both redirect foo.html to foo and rewrite foo to foo.html?Apache:如何将 foo.html 重定向到 foo 并将 foo 重写为 foo.html?
【发布时间】:2016-03-02 20:22:07
【问题描述】:

我正在托管一个只有一堆静态 .html 文件的网站。我不想在 URL 中包含 .html 文件扩展名,所以我添加了重写规则:

  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteCond %{REQUEST_FILENAME}\.html -f
  RewriteRule ^(.+)$ /$1.html [L]

这很简单并且工作正常,但我现在希望将以 .html 结尾的 (302) URL 重定向到规范路径,即没有文件扩展名。我尝试了以下方法:

  RewriteCond %{REQUEST_FILENAME} \.html$
  RewriteRule ^(.+)\.html$ /$1 [L,R]

  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteCond %{REQUEST_FILENAME}\.html -f
  RewriteRule ^(.+)$ /$1.html [L]

但是,这会导致无休止的重定向循环。我怀疑这是因为第二条规则,内部重写,仍然触发了第一条规则,外部重定向。

我还能如何做到这一点?我查看了所有的重写标志并尝试了一堆听起来很有希望的东西,但我还没有设法完成这项工作。我怎样才能既从foo.html重写为foo,又从foo内部重写为foo.html

【问题讨论】:

    标签: apache mod-rewrite url-rewriting url-redirection friendly-url


    【解决方案1】:

    several questions 询问此程序的工作原理。使用THE_REQUEST变量:

    RewriteCond %{THE_REQUEST} ^GET\ /(.+)\.html
    RewriteRule \.html$ /%1 [R=302]
    
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME}.html -f
    RewriteRule ^(.+)$ /$1.html [L]
    

    【讨论】:

    • 哎呀,让我怀疑我的 Google-Fu :( 效果很好。
    • 这非常有用。如何扩展它以使以下内容也有效? /foo => /foo/, /foo.html => /foo/ 和 /foo/ 保持原样,所有三个都返回 foo.html。谢谢。
    猜你喜欢
    • 2012-12-07
    • 2011-08-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-14
    • 2023-03-28
    • 1970-01-01
    相关资源
    最近更新 更多