【发布时间】:2013-07-16 13:54:18
【问题描述】:
如何使用 htaccess 文件将所有页面(仅限页面)重定向到 index.html,而不是重定向图像文件。出于某种原因,我正在使用此代码,并且 index.html 页面上的图像文件没有显示出来。
RewriteEngine on
RewriteCond %{REQUEST_URI} !^/index.html$
RewriteRule .* /index.html [L,R=302]
【问题讨论】:
如何使用 htaccess 文件将所有页面(仅限页面)重定向到 index.html,而不是重定向图像文件。出于某种原因,我正在使用此代码,并且 index.html 页面上的图像文件没有显示出来。
RewriteEngine on
RewriteCond %{REQUEST_URI} !^/index.html$
RewriteRule .* /index.html [L,R=302]
【问题讨论】:
试试这个代码:
RewriteEngine on
RewriteCond %{REQUEST_URI} !^/index.html$
RewriteCond %{REQUEST_URI} !\.(gif|jpe?g|png|css|js)$
RewriteRule .* /index.html [L,R=302]
【讨论】:
!\.(gif ...。否则,这可能会停止以这些字符结尾的目录上的匹配。也可以考虑使用[NC]。
保持规则简单。不要过滤不应该匹配的内容,只需匹配文件即可。
RewriteEngine on
RewriteCond %{REQUEST_URI} !^/index.html$
RewriteRule .*\.(php|html)$ /index.html [L,R=302]
【讨论】:
更好的方法可能是忽略现有文件。例如:
RewriteEngine on
RewriteCond %{REQUEST_URI} !^/$
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule .* / [L,R=302]
!-d 表示如果存在符合匹配项的现有目录,则忽略重写。
!-f 表示如果存在符合匹配的现有文件,则忽略重写。
其他所有内容都会被重写。
【讨论】:
您需要在public 目录中添加一个.htaccess 文件,因此每当您构建应用程序时,它都会自动复制到新的dist 目录中。 .htaccess 的内容应该是这样的:
RewriteEngine On
RewriteBase /
RewriteRule ^index.html$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.html [L]
【讨论】:
在最后一行之前添加以下内容
RewriteCond %{REQUEST_URI} !(\.png|\.jpg|\.gif|\.jpeg|\.bmp)$
【讨论】:
. 输出为!\.(png|jpe?g|gif|bmp)$ [NC]