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条)

报告相同问题?

悬赏问题

  • ¥20 修改光猫sn的时候提示失败
  • ¥15 java大作业爬取网页
  • ¥15 怎么获取欧易的btc永续合约和交割合约的5m级的历史数据用来回测套利策略?
  • ¥15 有没有办法利用libusb读取usb设备数据
  • ¥15 为什么openeluer里面按不了python3呢?
  • ¥15 关于#matlab#的问题:训练序列与输入层维度不一样
  • ¥15 关于Ubuntu20.04.3LTS遇到的问题:在安装完CUDA驱动后,电脑会进入卡死的情况,但可以通过键盘按键进入安全重启,但重启完又会进入该情况!
  • ¥15 关于#嵌入式硬件#的问题:树莓派第一天重装配置python和opencv后第二天打开就成这样,瞎捣鼓搞出来文件夹还是没把原来的界面调回来
  • ¥20 Arduino 循迹小车程序电路出错故障求解
  • ¥20 Arduino 循迹小车程序电路出错故障求解