doukun0888 2016-01-27 13:54
浏览 120
已采纳

htaccess将所有图像重定向到处理程序

What I want to do is redirect all images (jpeg, png, gifs?) to a index.php?q=file and that handler will use a <img src=file> tag.
But I'm afraid that when calling the file from that tag it will create an infinite loop.
So basically what I'm asking is how to redirect only outside calls to an image.
(Or is there a better way to protect my images?)

  • 写回答

2条回答 默认 最新

  • douxian7808 2016-01-27 13:59
    关注

    That rule creates a handler which takes all matching requests to imageHandler.php

    Please can you try the rule below;

    RewriteRule ^(.*)(.jpg|.jpeg|.png|.gif|.bmp|.etc)$ imageHandler.php?f=%{REQUEST_FILENAME} [QSA,L]
    

    And you will get $_GET["f"] as the file name which requested and the $_GET["f"] represents the path of the file on server.

    PS: This rule wont cause the infinite loop for your requests just imageHandler.php will execute some processes and you can decide return the file or not. Please mind that you have to implement a binary output for imageHandler.php which can cause cost for your operations. To reduce cost of that operation you may have to implement a client-cache or server-cache mechanism for imageHandler.php.

    That rule creates a redirect handler which redirects all matching requests to index.php

    RewriteCond %{HTTP_REFERER} ^$ #That means referer is empty which means direct access to file
    RewriteCond %{HTTP_REFERER} !^http://www\.example\.com.* #That means referer is not my domain because when you use a file in <img> tag that will create a request to that image with referer of embedding address
    RewriteCond %{REQUEST_URI} !^index.php  #That means request not targeted to index.php (which a part of endless loop)
    RewriteCond %{REQUEST_FILENAME} -f #That means request targeted to a file
    RewriteCond %{REQUEST_URI} (.jpg|.jpeg|.png|.gif|.bmp)$  #That means request ends with .ext
    RewriteRule ^(.*)(.jpg|.jpeg|.png|.gif|.bmp|.etc)$ http://example.com/index.php?f=$1 [R=302,L,QSA] #That means redirect request to index.php?f=file
    

    I do not have a chance to test second one due I do not have a linux environment but production and its not possible to test that in production environment.

    Hope these information helps you about your situation.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题
  • ¥15 wpf界面一直接收PLC给过来的信号,导致UI界面操作起来会卡顿
  • ¥15 init i2c:2 freq:100000[MAIXPY]: find ov2640[MAIXPY]: find ov sensor是main文件哪里有问题吗
  • ¥15 运动想象脑电信号数据集.vhdr
  • ¥15 三因素重复测量数据R语句编写,不存在交互作用
  • ¥15 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了