htaccess redirect all images to handler

对着背影说爱祢 提交于 2021-02-10 22:31:02

问题


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


回答1:


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.




回答2:


You can use this :

RedirectMatch ^/(.+\.(jpg|png|gif))$ /index.php?f=$1

This will redirect any request that ends with .jpg , png, or gif to /index.php.

Note that, this is an external redirection, You can use the rewriteRule provided by @cihanUygun ,if you want to internally redirect these requests to index.php.



来源:https://stackoverflow.com/questions/35039273/htaccess-redirect-all-images-to-handler

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!