0

On Apache Httpd 2.4, I know that from a .htaccess file I can do this

RewriteCond %{HTTP_ACCEPT} image/webp
RewriteCond %{DOCUMENT_ROOT}/$1.webp -f
RewriteRule (.+)\.jpg$ $1.webp [T=image/webp]

in order to implement content negotiation and for a jpg request, return a webp if the browser supports it.

Fine, I would like to send the request to Symfony when the webp file does not exists, so that a specific Symfony controller can create the webp version on demand, I know I could do this

RewriteCond %{HTTP_ACCEPT} image/webp
RewriteCond %{DOCUMENT_ROOT}/$1.webp -f
RewriteRule (.+)\.jpg$ $1.webp [T=image/webp]

RewriteCond %{HTTP_ACCEPT} image/webp RewriteCond %{DOCUMENT_ROOT}/$1.webp !-f RewriteRule (.+).jpg$ index.php [PT]

but this sends to Symfony the original jpg request, is it somehow possible from .htaccess rewrite to send to Symfony the webp request instead?

nulll
  • 539

1 Answers1

1
RewriteCond %{HTTP_ACCEPT} image/webp
RewriteCond %{DOCUMENT_ROOT}/$1.webp !-f
RewriteRule (.+)\.jpg$ index.php [PT]

but this sends to Symfony the original jpg request

Yes, but don't you need the original .jpg request in order to know how to generate the corresponding .webp image? The .webp URL-path is otherwise identical except for the file extension. You would then perform the same checks in your PHP code... you already know the .webp file does not exist, so you only need to check the Accept HTTP request header, generate the .webp image and serve it (or a 404 if there should be no image).

It's not possible to "rewrite" the request to webp and expect Symfony to pick this up without fundamentally altering the way Symfony checks the request. (Although I don't see why you would need to do this anyway, as mentioned above.)

You could perhaps pass a URL parameter to indicate to your script that a .webp image should be generated, but this does not negate the need for the same checks as above, so isn't really necessary. For example:

:
RewriteRule (.+)\.jpg$ index.php?generate-image=$1.webp [L]

The generate-image URL parameter then contains the document-root-relative (no slash prefix) URL-path of the .webp image to generate.

NB: You should be using the L flag on this rule, not PT. Your other rules should also include the L flag as well.

MrWhite
  • 13,315