Deny direct access but allow regular html

2019-07-25 09:06发布

问题:

I have the follow .htaccess inside upload directory:

order allow,deny
deny from all

I want to allow <img src="upload/image.png" /> but get forbbiden error (403).

How I can deny direct access but allow html "inclusion" (regular html)?

回答1:

You can't (reliably).

Whether viewed directly or as an <img> tag, the browser still makes a request to http://yoursite.example.com/upload/image.png, the two requests will basically be identical as far as the server is concerned.

Now in most browsers, the request from the <img> tag will be accompanied with a Referer: HTTP header which you can use in your Apache config to filter those requests, however:

  • This won't protect your image, they can be added by anyone trying to get the image, for example from the command line: curl -e 'http://my_referer.example.com' 'http://yoursite.example.com/upload/image.png'
  • After people have viewed the image via a web page, if they type the URL into their address bar the image is likely to be served from their browser cache and it will appear regardless of any server config you have in place


回答2:

You'll need mod_rewrite on,

RewriteEngine on
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^http://(www\.)?mydomain.com/.*$ [NC]
RewriteRule \.(gif|jpg|js|css)$ - [F]

Be sure to replace "mydomain.com" with your own.



回答3:

What are you trying to accomplish? You could base64 encode the images and place them inside the img tag's src attribute itself, using a technique similar to what is done here: http://www.greywyvern.com/code/php/binary2base64

There are possibly more advanced ways to obscure the image data, but ultimately you can't keep it from somebody who wants to hack around.