
Question:
I would like to know if it is possible to set up a redirect in the .htaccess
file so that if another website directly links to an image on my site, instead of the image opening in a browser window on its own, the page that the image is hosted on is displayed.
This page has the same name as the image i.e. if the image the other site is linking to is
<strong>Case1</strong>
www.example.com/subdirABC/gallery/image.jpg
**to**
www.example.com/subdirABC/
**or**
www.example.com/subdirABC/index.php
<strong>Case2</strong>
www.example.com/subdirXYZ/gallery/image.jpg
**to**
www.example.com/subdirXYZ/
**or**
www.example.com/subdirXYZ/index.php
Answer1:Its work for me
RewriteBase /
Options +FollowSymLinks
RewriteCond %{HTTP_REFERER} !^https://example.com
RewriteRule ^(.*)/gallery/(.*.jpg) /$1/ [L,R=301]
Answer2:Try something like the following in .htaccess
:
RewriteEngine On
RewriteCond %{HTTP_REFERER} !^https?://(www\.)?example\.com
RewriteRule ^([^/]+/)gallery/[\w-]\.jpg$ /$1 [R,L]
What this says is... for all requests that match the pattern /<subdir>/gallery/<filename>.jpg
and are not being linked to from your site (example.com
) then redirect to /subdir/
.
Additional notes...
<ul><li>Direct links (which includes search engine bots) and user-agents that fail to send the HTTP Referer
header will also be redirected to the "page".
<filename>
contains just the characters a-z
, A-Z
, 0-9
, _
and -
.
$1
is a backreference to the first captured group in the RewriteRule
<em>pattern</em>, ie. ([^/]+/)
- which matches subdirXYZ/
in your example.
This is a 302 (temporary) redirect.
</li> </ul>