Forum Moderators: phranque

Message Too Old, No Replies

Serving the right image even if request has extra subfolder

         

ntbgl

9:16 pm on Jun 9, 2009 (gmt 0)

10+ Year Member



My images are always placed in a folder that begins like:

http://www.example.com/uploads/thumb/...

However, some of my requests are a little different, like:

http://www.example.com/different_folder/uploads/thumb/..., or
http://www.example.com/different/folder/uploads/thumb/...

However, they still those images are still in examle.com/uploads/thumb/...

How can I modify my .htaccess to redirect those wrong image requests so they still the the right image instead of an error?

RewriteRule ^/(.*)/uploads/thumb/(.*)$ /uploads/thumb/$2 [L]

jdMorgan

9:34 pm on Jun 9, 2009 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



In .htaccess, I'd use:

RewriteRule ^[^/]+/uploads/thumb/(.+)$ http://www.example.com/uploads/thumb/$1 [R=301,L]

This 'fixes' the problem for your visitors and also tells the search engines to 'correct' those URLs in Image Search (if your images are indexed in Image Search).

Be sure that you fix any underlying errors on your site that are causing this incorrect-link problem, prior to installing the redirect. Otherwise, you subject your visitors to the delay of having to issue two HTTP requests for each image, and further, you fill up your server access log with unnecessary 301 redirect responses.

The most common error is to link to images from pages in rewritten 'pseudo-directories' using <img src="uploads/thumb/abc.jpg"> instead of using <img src="/uploads/thumb/abc.jpg"> or <img src="http://www.example.com/uploads/thumb/abc.jpg">. Since it is the client (e.g. browser) that resolves relative links based on the address in its address bar, the page-relative form of linking will fail if the 'directory' in the address bar isn't the real image directory or one of its parent directories. So, this is a very common problem when static-looking URLs are rewritten to a script for processing, and those static URLs contain directory-paths which do not physically exist. In that case, only server-relative or canonical links will resolve correctly; page-relative links will not.

If you have no other working rules in this .htaccess file, you will need either the second or both of these lines ahead of the rule:


Options +FollowSymLinks -MultiViews
RewriteEngine on

The only way to find out if you need the first line is to test without it first.

Jim