HartleySan
HartleySan

Reputation: 7830

How do I write an .htaccess file so that it can proxy images outside of the web root on an Apache server?

I want to proxy a bunch of images on my Apache server so that they are not stored in the webroot.
Specifically, I have all my images in the following folder on my Linux server:

/var/www/img/

However, I want it so that when a user goes to mydomain.com/img/img1.jpg (which has the server path /var/www/html/img/img1.jpg), it references the following file outside of the webroot:

/var/www/img/img1.jpg

It seems like this is possible using the ProxyPass and ProxyPassReverse rules in an .htaccess file (source: https://httpd.apache.org/docs/2.4/rewrite/avoid.html#proxy), but I'm having trouble understanding their syntax and which path goes where, etc.

Given my above situation, could someone please provide some explicit code that I can write into an .htaccess file to achieve what I want?


Edit: I just solved this problem by adding the following one line to my Apache httpd.conf file, and then restarting the server:

Alias "/img" "/var/www/img"

Where the /img part refers to the img directory in my webroot, and the /var/www/img part refers to the Linux filesystem directory I want to point to with the actual files in it.

Upvotes: 0

Views: 1035

Answers (2)

Michael Bissell
Michael Bissell

Reputation: 1208

Best way is to add a symbolic link to your other folder:

ln -s /my/target/folder /var/www/html/mynewfolder

If you can edit the Apache conf file for the server you need to add the FollowSymLinks directive in the directory block:

<Directory "/var/www/html/">
   AllowOverride All
   Options FollowSymLinks
</Directory>

You might also be able to add that to your .htaccess file as Options +FollowSymLinks if you can't edit the Apache file

Upvotes: 1

Panama Jack
Panama Jack

Reputation: 24478

You can try doing this with the PassThrough PT flag and mod_rewrite.

You create an alias to the actual path and then use it in the rule.

Alias "/img" "/var/www/img/"
RewriteRule "img/(.+)\.(jpe?g|gif|png)$" "/img/$1.$2" [PT]

See how that works for you.

Upvotes: 0

Related Questions