Mod_Rewrite条件有助于热链接但允许本地请求

时间:2012-09-16 21:58:44

标签: regex .htaccess mod-rewrite

我有热链接保护工作,所以我想,但不是因为推荐人是本地的。

IndexIgnore *
Options +FollowSymlinks
RewriteEngine on
RewriteOptions MaxRedirects=10

RewriteCond %{REQUEST_URI} ^/image_dir/
RewriteCond %{REQUEST_URI} \.(png|gif|jpe?g)$ [NC]
RewriteCond %{HTTP_REFERER} !^https?://(www\.)?domain.com/
RewriteRule ^(.*)$ /some_dir/some_file.php?querystring=$1 [L]

我需要的是:

如果在网站上的任何图片请求中,引荐来源不是来自我的网站,则会重定向到用户请求的图片页面。

如果引荐来自我的网站,而请求是针对image_dir中的任何图片,则重定向,否则不会。

非常感谢任何帮助!

编辑:这是完整的文件:

## Default .htaccess file
IndexIgnore *
Options +FollowSymlinks
RewriteEngine on
RewriteOptions MaxRedirects=10

# your rules were looping before, that's bad, this will stop it
RewriteCond %{ENV:REDIRECT_STATUS} 200
RewriteRule ^ - [L]

# redirect the browser back to the referring page
RewriteCond %{REQUEST_URI} ^/img/
RewriteCond %{REQUEST_URI} \.(png|gif|jpe?g)$ [NC]
RewriteCond %{HTTP_REFERER} !^https?://(www\.)?domain.com/
RewriteRule ^ %{HTTP_REFERER} [L,R]

# rewrite the request to the handler
RewriteCond %{REQUEST_URI} ^/img/
RewriteCond %{REQUEST_URI} \.(png|gif|jpe?g)$ [NC]
RewriteCond %{HTTP_REFERER} ^https?://(www\.)?domain.com/
RewriteRule ^(.*)$ /img/index.php?img_hash=$1 [L]


## Do pretty permalinks for our images
# these rules ensure you aren't clobbering legit requests (like to image.php) 
RewriteCond %{REQUEST_FILENAME} !-f 
RewriteCond %{REQUEST_FILENAME} !-d 

# just in case, exclude the admin directory 
RewriteCond %{REQUEST_URI} !^/admin [NC] 

# rewrite 
RewriteRule ^(.*)$ /display_image.php?img_hash=$1 [L] 

除了热链接之外,一切都像我想要的那样:

domain.com/t4hd -> domain.com/display_image.php?img_hash=t4hd (WORKS)
domain.com/t4hd.jpg -> domain.com/display_image.php?img_hash=t4hd.jpg (WORKS)
domain.com/img/t4hd -> domain.com/img/index.php?img_hash=t4hd (WORKS)
domain.com/img/t4hd.jpg -> domain.com/img/index.php?img_hash=t4hd.jpg (WORKS)
domain.com/img/123/456/789/t4hd.jpg -> domain.com/img/index.php?img_hash=t4hd.jpg (DOES NOT WORK)

我仍然必须允许所有请求:

domain.com/admin/index.php (WORKS)
domain.com/profile/index.php (WORKS)

希望这有助于澄清正在发生的事情。抱歉不要在开始时这样做。

1 个答案:

答案 0 :(得分:0)

请尝试使用这些规则:

# your rules were looping before, that's bad, this will stop it
RewriteCond %{ENV:REDIRECT_STATUS} 200
RewriteRule ^ - [L]

# redirect the browser back to the referring page
RewriteCond %{REQUEST_URI} ^/image_dir/
RewriteCond %{REQUEST_URI} \.(png|gif|jpe?g)$ [NC]
RewriteCond %{HTTP_REFERER} !^https?://(www\.)?domain.com/
RewriteCond %{HTTP_REFERER} !^$
RewriteRule ^ %{HTTP_REFERER} [L,R]

# rewrite the request to the handler
RewriteCond %{REQUEST_URI} ^/image_dir/
RewriteCond %{REQUEST_URI} \.(png|gif|jpe?g)$ [NC]
RewriteCond %{HTTP_REFERER} ^https?://(www\.)?domain.com/ [OR]
RewriteCond %{HTTP_REFERER} ^$
RewriteRule ^(.*)$ /some_dir/some_file.php?querystring=$1 [L]

也就是说,我在你的问题中假设这个神秘的位:

  

如果引荐来自我的网站,而请求是针对image_dir中的任何图片,则重定向,否则不会。

表示:

“如果引用来自我的网站,并且请求是针对image_dir中的任何图像,请将请求发送到some_file.php处理程序,否则不要执行任何操作。”