john smith
john smith

Reputation: 63

How to redirect an image changing the path using htaccess?

I am able to partially do this with the htaccess code below, but for some reason it's still adding some of the path before the image.

Here is my htaccess code:

RewriteCond %{REQUEST_FILENAME} .*jpg$|.*gif$|.*png$ [NC] 
RewriteCond %{HTTP_REFERER} !mysitee\.com [NC]
RewriteRule (.*)\.(jpg|gif|png)$ http://mysitee.com/?attachment=$1.$2

Essentially I need to remove the whole path except only for the filename and affix the end of the filename to a new path.

For example, one of the many images I have is:

http://mysitee.com/wp-content/uploads/2015/10/myimage.jpg

But when I use the code my new URL is this:

http://mysitee.com/?attachment=uploads/2015/10/myimage.jpg

I have many images, so obviously I can't just redirect each image separately.

How can I make this so it doesn't also add the path before the image? I want it to look like this:

http://mysitee.com/?attachment=myimage.jpg

Upvotes: 2

Views: 317

Answers (1)

hjpotter92
hjpotter92

Reputation: 80655

Just grab the last segment in your URL:

RewriteRule ([^/]*\.(jpg|gif|png))$ http://mysitee.com/?attachment=$1

Upvotes: 2

Related Questions