【问题标题】:.htaccess, Redirect Non-Existing Except a Few URL Rewrites.htaccess,重定向不存在的,除了少数 URL 重写
【发布时间】:2013-11-07 06:23:52
【问题描述】:

我有一个网页,如果用户 http://wwww.somewebsite.com/nonexistingfolderhttp://www.somewebsite.com/nonexistingfile.html 键入不存在的文件或文件夹,则只需将其转发到 www.somewebsite.com。然后想创建一个从 www.somewebsite.com/about.html 到 www.somewebsite.com/about 的网页,因为我认为越短越好。使用.htaccess 我想我可以将RewriteCond 用于不存在的内容,将RewriteRule 用于用户友好的网页网址。我在 .htaccess 方面很糟糕我只知道基础知识,我甚至对可能已经提出的问题进行了研究,但不知道如何编写此例外规则。

如何在.htaccess 中添加代码,以便我可以拥有除我指定的网页网址之外的所有不存在的文件/文件夹?。下面的这个将简单地将所有不存在的内容重定向到 index.html,当我执行 www.somewebsite.com/about(来自 /about.html)时,只需转到 index.html。有什么帮助吗?

--- my .htaccess shows --
# Redirect non-existing files or folders to index
<IfModule mod_rewrite.c>
  RewriteEngine on
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteRule ^(.*)$ / [L,QSA]
</IfModule>

# Rewrite existing files sample RewriteRule ^contact/$  /pages/contact.htm [L]
RewriteEngine on
RewriteRule ^/$    index.html [L]
RewriteRule ^about/$    about.html [L]
RewriteRule ^services/$    services.html [L]
RewriteRule ^application/$    application.html [L]
RewriteRule ^contact/$    contact.html [L]
RewriteRule ^privacy/$    privacy.html [L]

【问题讨论】:

    标签: .htaccess url-rewriting rewrite


    【解决方案1】:

    您需要在所有其他更具体的规则之后进行全有或全无的重写(例如RewriteRule ^(.*)$ / [L,QSA])。所有规则都按照它们出现的顺序被应用,所以这意味着你的第一条规则总是被应用,然后重写引擎停止。

    交换顺序再试一次:

    # Rewrite existing files sample RewriteRule ^contact/$  /pages/contact.htm [L]
    RewriteEngine on
    RewriteRule ^/?$    index.html [L]
    RewriteRule ^about/$    about.html [L]
    RewriteRule ^services/$    services.html [L]
    RewriteRule ^application/$    application.html [L]
    RewriteRule ^contact/$    contact.html [L]
    RewriteRule ^privacy/$    privacy.html [L]
    
    --- my .htaccess shows --
    # Redirect non-existing files or folders to index
    <IfModule mod_rewrite.c>
      RewriteEngine on
      RewriteCond %{REQUEST_FILENAME} !-f
      RewriteCond %{REQUEST_FILENAME} !-d
      RewriteRule ^(.*)$ / [L,QSA]
    </IfModule>
    

    还有这条规则:

    RewriteRule ^/$    index.html [L]
    

    永远不会被应用,因为在将规则应用到它们之前从 URI 中删除了前导斜杠,因此 ^/$ 永远不会匹配,您需要 ^$^/?$ 代替。

    【讨论】:

    • 我可能只是创建一个 404 错误页面,然后关闭对不存在的重写
    • @mythoslife 在这种情况下,您可以使用 mod_dir 的 FallbackResource 指令。
    • 很好用,我用过ErrorDocument 404 /404.html,我相信它很有效。但是现在我所有的自定义 URL 页面都将转到这个 404.html 页面。该死。
    • @mythoslife ErrorDocument 返回 404 错误,如果您希望它静默返回没有 404 响应的页面,则需要使用 FallbackResource
    • 哦,您只需输入FallbackResource /index.html 而不是RewriteCond。听起来不错。我有点困惑。
    猜你喜欢
    • 2016-05-23
    • 1970-01-01
    • 1970-01-01
    • 2016-08-20
    • 2013-12-21
    • 2015-03-04
    • 2014-11-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多