在.htaccess中编写规则以匹配正确的图像文件夹位置


Writing a rule in .htaccess to match the correct images folder location

在我的单页webapp中,我使用了html5历史API,这样url就可以有一个REST模式(/section1/stuff1..),我计划制作一种javascript路由器,根据url路径导航到页面的几个部分。

现在我仍然在本地服务器(wamp)上工作,我添加了一个。htaccess文件:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule (.*) index.php/$1 [L]

到应用程序的根url的路径包含对页面的某些部分的引用(例如subdomain/sectionN)总是可以重定向到index.php,重定向是成功的但是所有外部资源加载失败,我得到:

Resource interpreted as Image but transferred with MIME type text/html: "http://localhost/subdomain/section1/images/imgname.gif".

,这是合乎逻辑的,因为图像文件夹位于应用程序根目录下,而不是在/section1文件夹下,.htaccess规则RewriteRule (.*) index.php/$1 [L]应该只取/images/imgname.gif部分,并将其连接在http://localhost/subdomain/之后。

我发现这是一个类似的问题,所以我重写。htaccess文件如下:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^/?section1/(.+)$ index.php/$1 
RewriteRule (.*) index.php/$1 [L]

但是我得到了一个500 Internal Server Error

这两条规则:

RewriteRule ^/?section1/(.+)$ index.php/$1 
RewriteRule (.*) index.php/$1 [L]

可能同时应用于单个URL,因为在第一条规则之后没有[L](最后)标记。URL是这样的:

section1/stuff/page1.html

将被第一条规则转换为:

index.php/stuff/page1.html

,然后将被输入到第二条规则中并转换为:

index.php/index.php/stuff/page1.html

这很可能是导致500内部服务器错误的原因。如果您将[L]添加到第一条规则中,那么在第一条规则与URL匹配并且已应用的情况下,第二条规则将不会应用:

RewriteRule ^/?section1/(.+)$ index.php/$1 [L]

如果您不希望您的图像url被重写,那么只需删除第二个RewriteRule(这实际上使[L]冗余)。