htaccess Server-side WEBP detection in conjunction with WordPress htaccess rules

I have my htaccess file setup like so:

<IfModule mod_rewrite.c>
  RewriteEngine On
  # check if browser accepts webp
  RewriteCond %{HTTP_ACCEPT} image/webp 

  # check if file is jpg or png
  RewriteCond %{REQUEST_FILENAME} (.*).(jpe?g|png)$

  # check if corresponding webp file exists image.png -> image.webp
  RewriteCond %1.webp -f

  # serve up webp instead
  RewriteRule (.+).(jpe?g|png)$ $1.webp [T=image/webp,E=accept:1]

</IfModule>

<IfModule mod_headers.c>
  Header append Vary Accept env=REDIRECT_accept
</IfModule>

AddType image/webp .webp

Which works really well in a test directory, and shows a webp image if one is present. However, when I tried to use the same .htaccess rules in conjunction with WordPress’ pretty permalinks rewrite rules, the rules then break.

Read More

This is WordPress’ default rule (if your subdir is called DPA)

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /DPA/
RewriteRule ^index.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /DPA/index.php [L]
</IfModule>

I get the following error at the server if I try and access the jpg file directly:

The requested URL /wp-content/themes/dpa/assets/img/home-page/sliders/strategy-1650.webp was not found on this server.

Additionally, a 404 Not Found error was encountered while trying to use an ErrorDocument to handle the request.

I suppose this is because WordPress looks for files in the root and messes up the actual location of the image file.

Does anyone know rewrite rules well enough on apache to make the two rules compatible with each other?

Thanks!

Patrick

Related posts

Leave a Reply

1 comment

  1. This worked for me,

    <IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase /DPA/
    RewriteRule ^index.php$ - [L]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule . /DPA/index.php [L]
    </IfModule>
    
    <IfModule mod_rewrite.c>
      RewriteEngine On
      RewriteBase /DPA/
      # check if browser accepts webp
      RewriteCond %{HTTP_ACCEPT} image/webp 
    
      # check if file is jpg or png
      RewriteCond %{REQUEST_FILENAME} (.*).(jpe?g|png)$
    
      # check if corresponding webp file exists image.png -> image.webp
      RewriteCond %1.webp -f
    
      # serve up webp instead
      RewriteRule (.+).(jpe?g|png)$ $1.webp [T=image/webp,E=accept:1]
    
    </IfModule>
    
    <IfModule mod_headers.c>
      Header append Vary Accept env=REDIRECT_accept
    </IfModule>
    
    AddType image/webp .webp
    

    I added RewriteBase /DPA/ to the webp check and now it works fine.

    I just realised I included the default WordPress pretty permalinks code, but it should have been the one for directories. I will edit the question now.