Rewrite checking if file exists with different extensions

Using mod_rewrite to handle various content issues

Rewrite checking if file exists with different extensions

Postby shadowdani » Sun Feb 08, 2009 7:21 am

Hello

I am trying to build a rewrite rule that allows to match a request to different files (same name, but different extension), in particular, the rewrite url should first check if a file exists with one extension, if not go on to the second and so on.

I am currently using this rule:
Code: Select all
RewriteRule ^([^.]+)/$ cache/$1.html
RewriteRule ^([^.]+)$ cache/$1.html


The above rule matches requests such as /test/test (or with ending slash) to the appropriate file in the cache folder, including subfolders.

However I'm not able to add the appropriate rule to let it check/rewrite to the next possible extension, such as jpg. Here, with the same request and if the html file does not exist, the rule should try to match the request to a jpg file:
Code: Select all
RewriteRule ^([^.]+)$ cache/$1.jpg

Since the request has already been rewritten by the first rule, this second rule never applies and hence the jpg file is not found, even though it exists.

What could I do to solve this? Should I rewrite the request back prior to checking for the jpg file? Or is there a better way to solve this?

Thanks
shadowdani
 
Posts: 2
Joined: Sat Feb 07, 2009 2:58 pm

Postby richardk » Mon Feb 09, 2009 9:53 am

Try
Code: Select all
Options +FollowSymLinks

RewriteEngine On

# Check if a HTML file exists.
RewriteCond %{DOCUMENT_ROOT}/cache/$1.html -f
RewriteRule ^(.*[^/])/?$ /cache/$1.html [QSA,L]

# Check if a JPEG file exists.
RewriteCond %{DOCUMENT_ROOT}/cache/$1.jpg -f
RewriteRule ^(.*[^/])/?$ /cache/$1.jpg [QSA,L]


http://httpd.apache.org/docs/2.2/mod/mod_rewrite.html#rewritecond wrote:'-f' (is regular file)
Treats the TestString as a pathname and tests whether or not it exists, and is a regular file.
richardk
 
Posts: 8800
Joined: Wed Dec 21, 2005 7:50 am

Postby shadowdani » Mon Feb 09, 2009 10:33 am

Of course, I didn't even think of using a condition like that...

Thanks!
shadowdani
 
Posts: 2
Joined: Sat Feb 07, 2009 2:58 pm


Return to Content

Who is online

Users browsing this forum: No registered users and 12 guests

cron