The Vary: Accept HTTP response header is used when the content served by your application may vary based on the Accept header sent by the client. This is particularly useful when your server supports content negotiation for different media types, such as JSON, XML, or HTML.
You can add the Vary: Accept header dynamically in PHP by using the header() function.
Step-by-Step Guide
Add the Header in PHP
Use the header() function to include the Vary: Accept header in the HTTP response. This ensures that caches recognize that the resource might differ based on the Accept request header.
Example:
// Add the Vary: Accept header
header("Vary: Accept");
// Optional: Serve content based on the client Accept header
$acceptHeader = $_SERVER['HTTP_ACCEPT'];
if (strpos($acceptHeader, 'application/json') !== false) {
header('Content-Type: application/json');
echo json_encode(['message' => 'This is a JSON response']);
} elseif (strpos($acceptHeader, 'text/xml') !== false) {
header('Content-Type: text/xml');
echo '<?xml version="1.0"?><message>This is an XML response</message>';
} else {
header('Content-Type: text/html');
echo '<html><body><p>This is an HTML response</p></body></html>';
}
?>
When to Use Vary: Accept
You should use this header if:
- Your server or application delivers different representations of a resource (e.g., JSON, XML, or HTML) based on the Accept header in the request.
- You want to ensure that caching mechanisms (e.g., CDNs, browsers) store and serve the correct version for each type of Accept request.
Verify the Header
You can verify the Vary: Accept header using:
- Browser Developer Tools:
- Open the browser developer tools (F12).
- Go to the Network tab.
- Reload the page and inspect the response headers.
- cURL: Run the following command:
Look for the Vary: Accept header in the response.
Why Vary: Accept is Important
- Cache Differentiation: Ensures that CDNs, proxies, and browsers store separate versions of the resource based on the Accept request header.
- Content Negotiation: Properly informs caching mechanisms and clients that different representations are available.
- Improved SEO: Search engines like Google use Vary headers to index appropriate content versions (e.g., mobile-specific or JSON APIs).
Best Practices
- Use the Header Only When Necessary: Overusing Vary headers (e.g., Vary: Accept, User-Agent) can lead to cache fragmentation and reduced efficiency.
- Combine with Proper Cache-Control Headers: Ensure the resource has appropriate caching policies alongside the Vary header.
- Test Across Clients: Verify that different client requests receive the appropriate response type.
- Document Supported Media Types: Clearly document which Accept values your application supports for easier debugging and integration.
By adding the Vary: Accept header with PHP, you ensure proper caching and content negotiation for your application, improving performance and compatibility.


