【问题标题】:How to redirect all pages only to index.html using htaccess file and not redirect the image files如何使用 htaccess 文件仅将所有页面重定向到 index.html 而不重定向图像文件
【发布时间】:2013-07-16 13:54:18
【问题描述】:

如何使用 htaccess 文件将所有页面(仅限页面)重定向到 index.html,而不是重定向图像文件。出于某种原因,我正在使用此代码,并且 index.html 页面上的图像文件没有显示出来。

RewriteEngine on
RewriteCond %{REQUEST_URI} !^/index.html$
RewriteRule .* /index.html [L,R=302]

【问题讨论】:

    标签: image .htaccess


    【解决方案1】:

    试试这个代码:

    RewriteEngine on
    RewriteCond %{REQUEST_URI} !^/index.html$
    RewriteCond %{REQUEST_URI} !\.(gif|jpe?g|png|css|js)$
    RewriteRule .* /index.html [L,R=302]
    

    【讨论】:

    • 您的第二个条件也应该转义点!\.(gif ...。否则,这可能会停止以这些字符结尾的目录上的匹配。也可以考虑使用[NC]
    • 正是我试图向网站管理员提出的问题。谢谢!我将 302 更改为 301 并开始营业:) 我现在只需要重定向不在根目录中的所有图像。所以 /img/*gif|jpg|png 应该不理会,但 /subfolderNotImg|Js|Css 应该重定向
    • 其实我应该使用 410 Gone 而不是重定向
    • 您可能想要添加 svg|map|woff2|woff|ttf。用于加载 svg 图像、地图文件和网络字体。
    【解决方案2】:

    保持规则简单。不要过滤不应该匹配的内容,只需匹配文件即可。

    RewriteEngine on
    RewriteCond %{REQUEST_URI} !^/index.html$
    RewriteRule .*\.(php|html)$ /index.html [L,R=302]
    

    【讨论】:

      【解决方案3】:

      更好的方法可能是忽略现有文件。例如:

      RewriteEngine on
      RewriteCond %{REQUEST_URI} !^/$
      RewriteCond %{REQUEST_FILENAME} !-d
      RewriteCond %{REQUEST_FILENAME} !-f
      RewriteRule .* / [L,R=302]
      

      !-d 表示如果存在符合匹配项的现有目录,则忽略重写。

      !-f 表示如果存在符合匹配的现有文件,则忽略重写。

      其他所有内容都会被重写。

      【讨论】:

      • 我已经尝试了一切来完成这项工作。这是第一个这样做的。非常感谢。
      【解决方案4】:

      您需要在public 目录中添加一个.htaccess 文件,因此每当您构建应用程序时,它都会自动复制到新的dist 目录中。 .htaccess 的内容应该是这样的:

      
      RewriteEngine On
      RewriteBase /
      RewriteRule ^index.html$ - [L]
      RewriteCond %{REQUEST_FILENAME} !-f
      RewriteCond %{REQUEST_FILENAME} !-d
      RewriteRule . /index.html [L]
      
      

      【讨论】:

        【解决方案5】:

        在最后一行之前添加以下内容

        RewriteCond %{REQUEST_URI}  !(\.png|\.jpg|\.gif|\.jpeg|\.bmp)$
        

        【讨论】:

        • +1 但您可以将. 输出为!\.(png|jpe?g|gif|bmp)$ [NC]
        猜你喜欢
        • 2014-06-17
        • 1970-01-01
        • 2015-07-11
        • 2013-03-07
        • 1970-01-01
        • 2016-04-18
        • 2023-03-21
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多