HTTP 406 Response Status Code Guide: What is it, Usage, Methods

May 30 2024 by Oskay Günaçar

What Is HTTP 406 Status Code?

The HTTP 406 Status Code, also known as "Not Acceptable," is a client error response code indicating that the server cannot produce a response matching the list of acceptable values defined in the request's Accept headers. In other words, the server cannot fulfill the request using any of the content types specified in the Accept header of the request.

Common Causes

  1. Mismatched Content Types: The client requests a specific content type that the server cannot provide.
  2. Configuration Issues: The server might not be configured to handle the requested content type.
  3. Incorrect Accept Header: The client sends an Accept header that specifies content types not supported by the server.

Example

If a client sends a request with an Accept header specifying application/json and the server can only respond with text/html, the server will respond with a 406 status code:

GET /example
Accept: application/json
HTTP/1.1 406 Not Acceptable 

Importance of the HTTP 406 Status Code in SEO

The HTTP 406 Status Code, "Not Acceptable," plays a critical role in SEO (Search Engine Optimization) for several reasons:

1. Ensures Proper Content Delivery

By correctly handling the 406 status code, you ensure that your server delivers content in formats that match the client's capabilities. This guarantees that users and search engines receive content they can process, improving the overall user experience and accessibility of your site.

2. Improves Crawl Efficiency

Search engine bots crawl your site to index its content. If the server responds with a 406 status code due to unsupported content types, the bots can move on to other pages instead of wasting resources on content they cannot process. This efficient use of the crawl budget helps ensure that more relevant and accessible pages are indexed.

3. Prevents Indexing of Inappropriate Content

Handling the 406 status code prevents search engines from indexing error pages or content in inappropriate formats. This ensures that only valid and correctly formatted content is indexed, maintaining the quality of your site’s search engine listings.

4. Enhances User Experience

Properly managed content negotiation, reflected by appropriate use of the 406 status code, ensures users receive content in a format they can view. A positive user experience, characterized by easily accessible and correctly formatted content, leads to better engagement metrics like lower bounce rates and higher time on site, which are beneficial for SEO.

5. Clear Error Reporting

The 406 status code provides clear feedback about content type issues. This allows webmasters to quickly identify and address problems related to content negotiation. Timely fixes to these issues help maintain the site's health and functionality, which are critical for sustaining good SEO performance.

6. Content Negotiation Guidance

By returning a 406 status code, your server can inform clients (including search engine bots) about the acceptable content types. This guidance helps in properly managing requests and ensuring that clients request only those content types that the server can provide, leading to a more efficient and user-friendly website.

7. Security and Performance

Correctly implementing the 406 status code can prevent attempts to exploit content type misconfigurations. By securing the server against such vulnerabilities, you enhance the overall site performance and security, which are positive signals for search engine rankings.

How to Use HTTP 406 Status Code for a Website

To use the HTTP 406 status code effectively for a website, you need to ensure proper content negotiation between the client and the server. Here are the steps to implement and handle the 406 status code:

1. Define Supported Content Types

Clearly define which content types your server can deliver (e.g., JSON, HTML, XML). This helps in setting up the correct response based on the client's Accept header.

2. Inspect the Accept Header

In your server-side code, inspect the Accept header of the incoming request to determine if the requested content type is supported. If not, respond with a 406 status code.

3. Configure the Server

Ensure your server is configured to handle content negotiation properly and can respond with a 406 status code when necessary.

Example in Node.js/Express

const express = require('express');
const app = express();

app.get('/your-endpoint', (req, res) => {
    const accept = req.headers.accept || '';
    if (accept.includes('application/json')) {
        res.json({ message: 'This is a JSON response' });
    } else if (accept.includes('text/html')) {
        res.send('<p>This is an HTML response</p>');
    } else {
        res.status(406).send('Not Acceptable');
    }
});

app.listen(3000, () => {
    console.log('Server is running on port 3000');
});

4. Handle Content Negotiation in Different Frameworks

Here are examples for handling the 406 status code in different server environments:

Apache (Using .htaccess)

<FilesMatch "\.(html|json)$">
    AddType application/json .json
    AddType text/html .html
</FilesMatch>

In Apache, you can specify the content types your server should handle. If an unsupported type is requested, you can return a custom error page.

Nginx

server {
    location /your-endpoint {
        if ($http_accept !~* "application/json|text/html") {
            return 406;
        }
        
        # Normal processing
    }
}

In Nginx, you can use an if directive to check the Accept header and return a 406 status code if the requested content type is not supported.

5. Set the Allow Header

When responding with a 406 status code, include the Allow header to inform clients which content types are acceptable.

Example in Node.js/Express

app.get('/your-endpoint', (req, res) => {
    const accept = req.headers.accept || '';
    if (accept.includes('application/json')) {
        res.json({ message: 'This is a JSON response' });
    } else if (accept.includes('text/html')) {
        res.send('<p>This is an HTML response</p>');
    } else {
        res.set('Allow', 'application/json, text/html');
        res.status(406).send('Not Acceptable');
    }
});

6. Test Your Configuration

After setting up your server, test it to ensure that it responds correctly with a 406 status code when an unsupported content type is requested.

Using cURL (Command-Line Tool)

curl -H "Accept: application/xml" http://yourwebsite.com/your-endpoint 

Using Postman

  1. Open Postman.
  2. Enter the URL of your endpoint.
  3. Set an Accept header to a type not supported by your server.
  4. Click "Send" and check the response.

7. Provide Detailed Error Messages

Include clear error messages in your 406 responses to help clients understand why their request was not acceptable.

Example in Node.js/Express

app.get('/your-endpoint', (req, res) => {
    const accept = req.headers.accept || '';
    if (accept.includes('application/json')) {
        res.json({ message: 'This is a JSON response' });
    } else if (accept.includes('text/html')) {
        res.send('<p>This is an HTML response</p>');
    } else {
        res.set('Allow', 'application/json, text/html');
        res.status(406).json({
            error: 'Not Acceptable',
            message: 'The requested content type is not supported. Please use application/json or text/html.'
        });
    }
});

By following these steps, you can ensure that your server correctly handles content negotiation and returns the HTTP 406 status code when necessary, thereby improving the user experience and maintaining the integrity of your web application's responses.

How to Check HTTP 406 Status Code?

To check if your server correctly responds with an HTTP 406 status code, you can use several methods, including command-line tools, browser developer tools, and online services. Here are the steps for each method:

1. Using cURL (Command-Line Tool)

cURL is a powerful command-line tool for making HTTP requests. You can use it to send a request with an unsupported Accept header to your server and check the response.

Example Command:

curl -H "Accept: application/xml" http://yourwebsite.com/your-endpoint 
  • Replace http://yourwebsite.com/your-endpoint with the actual URL of your endpoint.
  • This command sends a request with Accept: application/xml, which should trigger a 406 response if application/xml is not supported by your server.

2. Using Postman

Postman is a popular tool for testing APIs.

Steps:

  1. Open Postman.
  2. Enter the URL of your endpoint in the request URL field.
  3. Select the HTTP method (e.g., GET).
  4. In the Headers tab, add a new header with the key Accept and a value of an unsupported content type (e.g., application/xml).
  5. Click "Send."
  6. Check the response status code in the Postman interface. It should be 406 if the method is not allowed.

3. Using Browser Developer Tools

Most modern web browsers have built-in developer tools that allow you to inspect HTTP responses.

Steps:

  1. Open your browser (Chrome, Firefox, etc.).
  2. Open Developer Tools (usually by right-clicking on the page and selecting "Inspect" or pressing F12).
  3. Go to the "Network" tab.
  4. Make a request using a method that is not allowed (e.g., using a form submission with a method not supported).
  5. Check the network log for the request and inspect the response status code.

4. Using Online Services

Several online tools can test HTTP responses, such as ReqBin, HTTP Status Code Checker, and others.

Steps:

  1. Go to an online HTTP status checker (e.g., ReqBin).
  2. Enter the URL of your endpoint.
  3. Set the Accept header to an unsupported content type (e.g., application/xml).
  4. Send the request and check the response status code. It should be 406 if the method is not allowed.

5. Using a Script

If you prefer scripting, you can use languages like Python to send HTTP requests and check the response.

Example in Python:

import requests

url = 'http://yourwebsite.com/your-endpoint'
headers = {
    'Accept': 'application/xml'
}
response = requests.get(url, headers=headers)

print(response.status_code)
  • Replace http://yourwebsite.com/your-endpoint with the actual URL of your endpoint.
  • This script will print the status code of the response, which should be 406 if the content type is not supported.

By using these methods, you can verify whether your server correctly responds with an HTTP 406 status code when an unsupported content type is requested. This helps ensure that your content negotiation is properly implemented and that clients are informed about acceptable content types.

Best Practices for Handling HTTP 406 Status Code

Handling the HTTP 406 status code effectively involves implementing best practices that enhance the user experience, improve communication between client and server, and maintain application robustness. Here are some best practices:

1. Define Supported Content Types Clearly

Ensure that each endpoint explicitly specifies the content types it supports.

  • Server Configuration: Configure your server to define acceptable content types.
  • API Documentation: Clearly document supported content types in your API documentation so that clients know what formats are acceptable.

2. Proper Server Configuration

Configure your server to respond appropriately when an unsupported Accept header is encountered.

  • Apache Configuration: Use the AddType directive to specify supported content types.
  • Nginx Configuration: Use the types directive to define supported content types.

3. Application-Level Handling

In your application code, handle unsupported content types explicitly and return a 406 status code.

Example in Node.js/Express:

app.get('/your-endpoint', (req, res) => {
    const acceptedTypes = req.accepts(['json', 'html']);
    if (!acceptedTypes) {
        res.status(406).send('Not Acceptable');
        return;
    }
    // Handle request
});

4. Include the Accept Header

When sending a 406 response, include the Accept header to inform clients of the supported content types.

app.get('/your-endpoint', (req, res) => {
    const acceptedTypes = req.accepts(['json', 'html']);
    if (!acceptedTypes) {
        res.set('Accept', 'application/json, text/html');
        res.status(406).send('Not Acceptable');
        return;
    }
    // Handle request
}); 

5. Provide Detailed Error Messages

Provide clear and concise error messages to help clients understand why the request was rejected.

res.status(406).json({ error: 'Not Acceptable', message: 'Supported content types are application/json and text/html.' }); 

6. Logging and Monitoring

Log all 406 responses to monitor and analyze content negotiation issues.

  • Use logging tools and services to track these events.
  • Analyze logs to understand common issues and improve your API or web application.

7. Testing and Validation

Regularly test your endpoints to ensure they correctly handle unsupported content types.

  • Automated Tests: Use automated tests to validate that 406 responses are returned as expected.
  • Manual Tests: Periodically perform manual tests using tools like Postman, cURL, or browser developer tools.

8. Security Considerations

Be mindful of security implications and ensure that your server does not expose unnecessary content types that could be exploited.

  • Regularly review and update your content type handling policies as part of your security practices.

9. Graceful Degradation

If possible, provide alternative suggestions or guidance when a 406 response is triggered, helping users to correct their requests.

  • Offer alternative content types that the server can provide.
  • Provide links to documentation or support resources.

10. Content Negotiation

Implement proper content negotiation to handle multiple content types and provide the best possible response to clients.

  • Use libraries or frameworks that support content negotiation.
  • Ensure that your server can handle different Accept headers and return appropriate responses.

By following these best practices, you can ensure that your application correctly handles HTTP 406 status codes, improving user experience and communication between client and server. Proper handling of this status code helps maintain the robustness and reliability of your web application or API.

Conclusion

The HTTP 406 status code, "Not Acceptable," plays a crucial role in maintaining effective communication between clients and servers by ensuring proper content negotiation. Correctly handling this status code not only improves user experience by delivering content in acceptable formats but also enhances crawl efficiency, prevents the indexing of inappropriate content, and supports the overall health of your website. By implementing best practices such as defining supported content types, configuring the server correctly, providing detailed error messages, and performing regular testing and validation, you can ensure that your application robustly handles HTTP 406 responses. This proactive approach helps in maintaining a secure, efficient, and user-friendly website, ultimately benefiting your site's SEO performance and reliability.

Oskay Günaçar
Oskay Günaçar is a Technical SEO expert and backend developer. His main areas of interest are back-end programming, Python, Django, Go, semantic SEO, technical SEO. With more than 5 years of SEO experience, he has held SEO specialist positions at İkiler, Webtures, Boosmart, and Storyly.io companies, and has been involved in numerous projects as an outsourced expert. Through the TechSEOHub website, he aims to share the expertise and experience he has gained from managing and developing (SEO) processes for many successful and large websites in the industry, and to produce content for easy access to accurate and high-quality information.