To set up your .htaccess file so that image requests automatically redirect to webp-on-demand.php when the browser supports WebP, you need to ensure that the rewrite rules are correctly ordered and properly configured. Below is a refined version of your .htaccess file with explanations and best practices applied:
# Enable Rewrite Engine
RewriteEngine On
# 1. Redirect all HTTP requests to HTTPS
RewriteCond %{HTTPS} off
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
# 2. Serve WebP images if the browser supports WebP
# This rule should come before other rewrite rules to ensure it's processed first.
RewriteCond %{HTTP_ACCEPT} image/webp
RewriteCond %{REQUEST_FILENAME} -f
RewriteRule ^(.+)\.(jpe?g|png)$ /includes/webp-on-demand.php?source=$0 [QSA,L]
# 3. Rewrite URLs to append .php if the requested resource isn't a directory
# and the corresponding .php file exists.
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.+)$ $1.php [NC,L]
# 4. Add WebP MIME type for proper handling
AddType image/webp .webp
Detailed Breakdown:
-
Enable Rewrite Engine:
RewriteEngine On
This line activates the Apache rewrite engine, allowing the subsequent rewrite rules to function.
-
Redirect HTTP to HTTPS:
RewriteCond %{HTTPS} off
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
- Condition: Checks if the request is not using HTTPS.
- Rule: Redirects the request to the same URL but with HTTPS.
- Flags:
R=301: Performs a permanent redirect.
L: Stops processing further rules if this rule matches.
-
Serve WebP Images If Supported:
RewriteCond %{HTTP_ACCEPT} image/webp
RewriteCond %{REQUEST_FILENAME} -f
RewriteRule ^(.+)\.(jpe?g|png)$ /includes/webp-on-demand.php?source=$0 [QSA,L]
- Conditions:
- Checks if the
Accept header includes image/webp, indicating browser support.
- Verifies that the requested file exists.
- Rule: Redirects image requests (JPEG or PNG) to
webp-on-demand.php, passing the original image path as a query parameter.
- Flags:
QSA: Appends any existing query string to the new query string.
L: Stops processing further rules if this rule matches.
- Note:
-
Append .php to Requests If Applicable:
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.+)$ $1.php [NC,L]
- Conditions:
- Ensures that the request is not pointing to a directory.
- Checks if a corresponding
.php file exists.
- Rule: Internally rewrites the URL to include the
.php extension.
- Flags:
NC: Makes the rule case-insensitive.
L: Stops processing further rules if this rule matches.
-
Add WebP MIME Type:
AddType image/webp .webp
This line ensures that .webp files are served with the correct MIME type, allowing browsers to recognize and display them properly.
Additional Recommendations:
-
Ordering of Rules: The order of the rewrite rules is crucial. Place the WebP handling rules before other rewrite rules to ensure they are processed first. This prevents other rules from interfering with image redirections.
-
Caching Considerations: To improve performance, especially for images, consider adding caching headers. For example:
<FilesMatch "\.(jpe?g|png|webp)$">
Header set Cache-Control "max-age=31536000, public"
</FilesMatch>
-
Testing: After updating your .htaccess file, thoroughly test the configuration:
- Use different browsers to confirm that WebP images are served when supported.
- Ensure that non-image requests and unsupported image formats are handled correctly.
- Check redirections from HTTP to HTTPS work as expected.
-
Error Logging: If you encounter issues, enable Apache's rewrite logging to debug:
RewriteLog "/path/to/rewrite.log"
RewriteLogLevel 3
Note: Logging can impact performance and should be disabled (RewriteLogLevel 0) in a production environment.
Example webp-on-demand.php Script:
Ensure your webp-on-demand.php script correctly processes the source parameter and serves the appropriate WebP or fallback image. Here's a basic example:
<?php
// webp-on-demand.php
// Get the source image path from the query parameter
$source = $_GET['source'] ?? '';
if (!$source) {
header("HTTP/1.0 400 Bad Request");
exit('No source specified.');
}
// Sanitize the input to prevent security issues
$source = realpath($_SERVER['DOCUMENT_ROOT'] . '/' . ltrim($source, '/'));
if (!$source || !file_exists($source)) {
header("HTTP/1.0 404 Not Found");
exit('Image not found.');
}
// Check if WebP is supported by the browser
if (strpos($_SERVER['HTTP_ACCEPT'], 'image/webp') !== false) {
$webpSource = $source . '.webp';
if (file_exists($webpSource)) {
header('Content-Type: image/webp');
readfile($webpSource);
exit;
} else {
// Optionally, you can dynamically convert the image to WebP here
// For simplicity, we'll fallback to the original image
}
}
// Fallback to the original image type
$mime = mime_content_type($source);
header("Content-Type: $mime");
readfile($source);
exit;
?>
Summary:
By organizing your .htaccess file as shown and ensuring that your webp-on-demand.php script is correctly implemented, you can efficiently serve WebP images to supported browsers while maintaining compatibility with browsers that do not support WebP. This setup improves image loading performance and reduces bandwidth usage where possible.