【问题标题】:Rewriting URL by appending .html suffix通过附加 .html 后缀重写 URL
【发布时间】:2015-11-30 13:06:06
【问题描述】:

我正在尝试在 Apache 2.4 中使用 mod_rewrite 来附加后缀 .html 来请求 URI。

应该重写的 URI 非常简单,格式如下:

http://host.domain/page/

以上需要重写为http://host.domain/page.html。唯一的限制是重写逻辑必须忽略引用实际文件或目录的 URI。

到目前为止,如果 没有尾随斜杠,我想出的重写 sn-p 工作正常,但是如果存在斜杠,Apache 会发出 404 和以下错误消息:

The requested URL /redirect:/about.html was not found on this server.

(当URI为http://localhost/about/时会发生上述情况)

有人可以帮我调试一下吗?为什么 Apache 在前面加上 /redirect:

这是一个重现症状的非常简单的 sn-p:

RewriteEngine on

RewriteBase /

RewriteRule ^(.+[^/])/$ /$1 [C]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !^$
RewriteRule (.*) /$1.html [L,R=301] # Tried without R=301 too

# This doesn't work either.
# RewriteRule ^about/$ /about.html [L,R=301]

【问题讨论】:

    标签: apache .htaccess mod-rewrite apache2.4


    【解决方案1】:

    你可以使用:

    RewriteEngine on
    RewriteBase /
    
    # strip trailing slash from non-directoies
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.+?)/$ /$1 [L,R=301]
    
    # make sure corresponding html file exists
    RewriteCond %{DOCUMENT_ROOT}/$1\.html -f
    RewriteRule ^(.+?)/?$ $1.html [L]
    

    【讨论】:

    • 你能解释一下我上面哪里出错了吗?例如,为什么不链接第一条规则以删除尾部斜杠?
    • 第一条规则中不需要使用C标志,最好使用RewriteCond %{DOCUMENT_ROOT}/$1\.html -f来确保对应的html文件存在。
    猜你喜欢
    • 1970-01-01
    • 2012-02-21
    • 1970-01-01
    • 1970-01-01
    • 2011-01-13
    • 2016-06-27
    • 2017-06-01
    • 1970-01-01
    • 2016-03-30
    相关资源
    最近更新 更多