【问题标题】:Writing a rule in .htaccess to match the correct images folder location在 .htaccess 中编写规则以匹配正确的图像文件夹位置
【发布时间】:2015-05-17 16:21:42
【问题描述】:

在我的单页 web 应用程序中,我使用了 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]

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

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

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

我发现this 是一个类似的问题,所以我像这样重写 .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

【问题讨论】:

    标签: php regex .htaccess mod-rewrite wampserver


    【解决方案1】:

    这两条规则:

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

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

    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] 变得多余)。

    【讨论】:

    • 我将 [L] 从最后一行移到上一行,但仍然出现 500 错误,因为实际上重定向需要这两个规则,因为即使是 url localhost/subdomain/section1 也应该由规则处理最后一行 (RewriteRule (.*) index.php/$1) as section1 本身只是 DOM 的子元素,而不是页面。
    • 更改最后两行的顺序并没有解决它,因为看起来一旦处理了第一个 RewriteRule(RewriteRule (.*) index.php/$1)它就不会给出交给下一条规则。
    • 我做错了;这不是我需要的串行处理,而是 RewriteRule ^/?section1/(.+)$ index.php/$1 规则应该只处理特定于某些文件扩展名(.png、.jpg、..)的 url。怎么可能?
    • 您能否编辑您的问题以提供一些输入 URL 的示例以及应用规则后所需的输出?
    • 如果您希望规则仅适用于某些扩展,您可以执行以下操作:RewriteRule ^/?section1/(.+(?:jpe?g|gif|bmp|png))$ index.php/$1
    猜你喜欢
    • 2016-05-15
    • 2021-04-30
    • 1970-01-01
    • 1970-01-01
    • 2010-11-09
    • 2017-07-16
    • 2012-11-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多