The following are scripting examples of content negotiation using the HTTP Accept header.
These examples are used to properly serve XHTML with the proper MIME media type of application/xhtml+xml. If the request header does not allow this media type, it will be served as text/html. This convention follows the W3C standard for “Recommended Media Type Usage:”
1. If the Accept header explicitly contains application/xhtml+xml (with either no “q” parameter or a positive “q” value) deliver the document using that media type.
2. If the Accept header explicitly contains text/html (with either no “q” parameter or a positive “q” value) deliver the document using that media type.
3. If the accept header contains “*/*” (a convention some user agents use to indicate that they will accept anything), deliver the document using text/html.
Apache .htaccess file
RewriteCond %{HTTP_ACCEPT} application/xhtml\+xml
RewriteCond %{HTTP_ACCEPT} !application/xhtml\+xml\s*;\s*q=0\.?0*(\s|,|$)
RewriteCond %{REQUEST_URI} \.html$
RewriteRule .* - [T=application/xhtml+xml;charset=utf-8]
RewriteCond %{HTTP_ACCEPT} application/xhtml\+xml
RewriteCond %{HTTP_ACCEPT} !application/xhtml\+xml\s*;\s*q=0\.?0*(\s|,|$)
RewriteCond %{REQUEST_URI} !\.
RewriteRule .* - [T=application/xhtml+xml;charset=utf-8] |
PHP
<?php if ( stristr($_SERVER["HTTP_ACCEPT"],"application/xhtml+xml") ) { header("Content-type: application/xhtml+xml"); } else { header("Content-type: text/html"); } ?> |
CGI Script
import os if os.environ.get('HTTP_ACCEPT', '').find('application/xhtml+xml') > -1: print 'Content-type: application/xhtml+xml' else: print 'Content-type: text/html' |
Ruby (for rails)
<% if @request.env["HTTP_ACCEPT"].index('application/xhtml+xml') @headers["Content-Type"] = "application/xhtml+xml; charset=utf-8" else @headers["Content-Type"] = "text/html; charset=utf-8" end %> |

