Reading the comments, I'd recommend to avoid maintaining N RewriteRule
s for N images. Such a setup will turn into a maintenance nightmare for the site admin who will need to copy and paste a new rule for every new image on the site. And if you ever need to change the rules, well... good luck with that.
If you have the flexibility to choose a better directory structure, it can simplify your .htaccess file down to a single rewrite rule. In that case, you can choose a directory structure where given a path to an image you can easily determine the path to the page it belongs to. For example:
root/
.htaccess
page1/
index.html
image/
image1.jpg
image2.jpg
page2/
index.html
image/
img.jpg
Here the rewrite definition within root/.htaccess
is simple (adapted from @jon-lin's answer):
# Rewrite any image URL `/<page>/images/*` to `/<page>/`.
RewriteEngine On
RewriteCond %{HTTP_REFERER} !^https?://mysite\.com/
RewriteRule ^([^/]+)/image/ /$1/ [L,R]
Pros
- One
RewriteRule
to rule them all.
- Your images do not have to be .jpg, as long as they reside in
/<page>/image/
.
Cons
- Need to reorganize existing files.
- Directory structure very tailored to the rewriting problem. It would be awkward for a page to access an image which "belongs" to another page.