.htaccess rule to redirect direct view of image file to a page, with image passed as a query string

Viewed 98

I'd like if someone tries to visit any image in this folder directly: https://www.example.com/map-images/example-image-123.jpg

They get redirected to a page, passing the image name as a query string, and end up here: https://www.example.com/map-image-viewer?imagename=example-image-123.jpg

Clarifications: On the map-image-viewer page, I need to be able to use the example-image-123 as a src in an iframe (even though I am disallowing direct access to the image in the map-images folder). Note that I do NOT want to block image access with a Forbidden flag as I DO want the images to be able to be indexed by search engines. Not sure if that's possible?

Update: I tried the following, and it DOES redirect viewing of the particular image to the map-image-viewer page, passing the imagename as a query parameter. However, the image can no longer be used as a src in an iframe on the map-image-viewer page:

RewriteCond %{REQUEST_URI} ^/map-images/(.*)$
RewriteRule ^(.*) /map-image-viewer?imagename=%1 [R=301,L]

I'm probably missing something obvious, but would appreciate the help :)

1 Answers

You are almost set just put one more condition in your rules. I have added condition to check condition if query string is null then only redirect by this we will not be stuck in infinite redirect loop, fixing OP's attempt here.

Please make sure you clear your browser cache before testing any URLs.

RewriteEngine ON
RewriteCond %{REQUEST_URI} ^/map-images/(.*)/?$ [NC]
RewriteCond %{QUERY_STRING} ^$
RewriteRule ^(.*)$ map-image-viewer?imagename=%1 [R=301,L]
Related