Redirect raw .gif files to handler page via .htacc

2019-07-20 09:03发布

问题:

I have a viral image site where people can view funny gifs. A lot of people on reddit are sharing the raw .gif files however, rather than the page with .gif embedded. This is fine - but I'd like to redirect all people viewing raw image .gifs to a handler page called shareraw.php (located in root directory). This handler page will look exactly the same - just with a share link and button to check out the rest of the site.

I've created the page. All I need now is the correct .htaccess commands to do what I've described. Please help! Thanks :)

回答1:

You can do this by checking the HTTP_REFERER for .gif requests. If the request isn't coming from your site, you redirect the user to your shareraw.php file.

Add this to your .htaccess in your web root / directory.

Options +FollowSymLinks -MultiViews
RewriteEngine on

RewriteCond %{HTTP_REFERER} !^http://(www\.)?mysite\.com/ [NC]
RewriteCond %{REQUEST_URI} /uploads/.*\.gif$ [NC]
RewriteRule ^(.*)$ /shareraw.php?img=$1 [R,L]

You'll just need to tweak the rules to accomodate where your viral gifs are stored and how the gif name or path is passed to your shareraw.php.