【问题标题】:How to url-rewrite image request?如何url-rewrite图像请求?
【发布时间】:2016-10-06 10:03:48
【问题描述】:

我正在使用 url 重写。这里有很多很好的信息,我有一个可行的解决方案,但我想做得更好。

我的有限解决方案

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RedirectMatch (.*)\.(gif|jpg|png)$ http://www.somesite.com$1.$2
RewriteRule ^(.*)$ /index.php?q=$1 [L,QSA]

上述重定向图像请求很好,但我正在用多种语言构建多个站点,我想通过以下方式改进:

/attachments/1/canada-flag-small.1.jpg -> http://www.somesite.com/attachments/1/1.jpg
/jointes/2/usa-petit.1001.png -> http://www.somesite.com/attachments/2/1001.png

基本上,括号内的所有扩展 (gif|jpg|png) 都应重定向到 http://www.somesite.com/attachments。所以需要完全忽略图像源中的第一个标记。

图像源中的第二个标记很重要,因为它是存储图像的目录,它应该包含在重写的 url 中。

图像源中的图像名称应该被忽略,但名称后面的图像ID和扩展名需要形成我们重定向到的图像名称。

如果它更容易,图像名称中不会有斜线。

我自己的尝试导致内部服务器错误。希望这里有人愿意看看这个。我见过类似的例子,人们从图像 id 开始,添加破折号,然后添加描述性图像名称。我更喜欢使用上面显示的样式,因为我将拥有诸如“3-wheel-atv.333.jpg”之类的图像,并且我不想混淆图像 ID 的位置。

Croises 提供的所需解决方案

RewriteRule ^[^/]+/([^/]+)/(?:.*?\.)?(\d+\.(gif|jpg|png))$ http://www.somesite.com/attachments/$1/$2 [NC,L]

这允许将图像存储为附件/文件夹 1/1.jpg,但可用于具有 /great-images/folder1/awesome-image.1.jpg 等来源的页面。

【问题讨论】:

    标签: image .htaccess url-rewriting


    【解决方案1】:

    尝试:

    RewriteEngine on
    
    RewriteRule ^[^/]+/([^/]+)/(?:.*?\.)?(\d+\.(gif|jpg|png))$ http://www.somesite.com/attachments/$1/$2 [NC,L]
    
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)$ /index.php?q=$1 [L,QSA]
    

    如果你的第二个标记,存储图像的目录,只是一个数字,你可以使用:

    RewriteRule ^[^/]+/(\d+)/(?:.*?\.)?(\d+\.(gif|jpg|png))$ http://www.somesite.com/attachments/$1/$2 [NC,L]
    

    【讨论】:

    • 谢谢,Croises。这似乎工作得很好。我明天再做一些测试并报告。
    猜你喜欢
    • 2011-01-09
    • 1970-01-01
    • 2018-12-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多