Question

I want to do an .htaccess rewrite for an image uploader I have on my site, but for all the tutorials I've tried, I can’t get it working.

Currently, the code I have uploads images to the folder: http://www.example.com/server/php/files/jkgh4f54.jpg

I’d like to rewrite it so when you go to this URL: http://www.example.com/jkgh4f54.jpg it is showing the image from the above location.

Any thoughts? As I mentioned, there are a lot of tutorials everywhere about stuff similar to this, but I haven't been able to adapt them to work thus far for me.

Current .htaccess:

RewriteEngine On
RewriteCond %(REQUEST_FILENAME} !-f [OR]
RewriteCond %(REQUEST_FILENAME} !-d
RewriteRule ^[a-zA-Z0-9]+\.(jpe?g|png|gif|bmp)$ /server/php/files/$0 [L]
RewriteRule ^([a-zA-Z0-9]+)$ index.php?code=$1 //For URL Shortener
ErrorDocument 404 http://localhost/site.com/404.php
Was it helpful?

Solution

Using this code, when the user visits http://example.com/h3h2js.jpg, they will see the image from http://example.com/server/php/files/h3h2js.jpg, but the URL in the browser will stay the same:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f [OR]
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^[a-zA-Z0-9]+\.(jpe?g|png|gif|bmp)$ /server/php/files/$0 [L]

I have tested this code thoroughly on a clean installation of XAMPP on Windows. Image names must only contain alphanumeric characters of either case (a-z, A-Z, 0-9), and must end with a jpg, jpeg, png, gif or bmp file extension. If the requested image file already exists in the site root, the rewrite will not take place

OTHER TIPS

Try:

RewriteEngine on
RewriteRule ^(.*)\.jpg$ http://site.com/server/php/files/$1\.jpg [R=301,L]
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top