【问题标题】:Rewrite resource URL to serve files from subdirectory重写资源 URL 以提供来自子目录的文件
【发布时间】:2014-04-14 14:43:34
【问题描述】:

我有一个使用 资源标签(图像、css、脚本)的静态 HTML 站点,如下所示:

<html>
    <head><title>htaccess test page</title></head>
    <body>
        <img src="/img/img.jpg" alt="...">
    </body>
</html>

当我在浏览器中加载 html 文件时,请求是:

http://localhost/img/img.jpg(可以理解地返回 404)

我希望向哪里提出请求:

http://localhost/site/img/img.jpg

目录结构如下:

- www
    - site
        - .htaccess
        - img
            - img.jpg

我一直在寻找解决方案,并且模糊地认为 RewriteCond 是可行的方法,但我无法让它发挥作用:

RewriteEngine On
# if requested URI is not a file
RewriteCond %{REQUEST_FILENAME} !-f
# serve the file from the img directory, yes, very limited,
# and requires me to add rules for scripts, css etc.
RewriteRule ^(.*)$ img/$1 [L]

任何帮助将不胜感激。 SO 为这个问题返回了很多解决方案,但它们似乎都不起作用。

【问题讨论】:

    标签: .htaccess apache2


    【解决方案1】:

    您的解决方案将以这种方式处理每个文件,并将重新路由它。有了这个 RewriteRule,只有图像会被重定向到 /site/{HTML 中定义的图像的路径}

    RewriteRule ([^.]+\.(jpe?g|gif|bmp|png))$ /site/$1 [R=301,L,NC]
    

    你应该把图片像这样&lt;img src="img/img.jpg" alt="..."&gt;

    最终版本如下所示:

    RewriteEngine On  
    # if requested URI is not a file
    RewriteCond %{REQUEST_FILENAME} !-f
    # image part
    RewriteRule ([^.]+\.(jpe?g|gif|bmp|png))$ /site/$1 [R=301,L,NC]
    

    【讨论】:

    • 这似乎不起作用,而且,我无法更改 &lt;img src="..."&gt; 尽管我知道更改 src 属性将解决此问题。
    • 将“/”放在开头是一种不好的做法。如果这不是您的代码,那很好。我已经更新了答案,它对我有用。
    猜你喜欢
    • 1970-01-01
    • 2016-07-08
    • 1970-01-01
    • 2020-11-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多