Search code examples
amazon-s3http-response-codes

How to change http response code on an object in Amazon S3


I have a webpage hosted on Amazon S3 but I don't want the http response code to be 200. The page is a maintenance page that I'll redirect traffic to when I take our main website down for maintenance.

I want the Amazon S3 page to include a response header of:

HTTP/1.1 503 Service unavailable

Amazon give the ability to add some metadata to the S3 Object but there is nothing for the http status code.

Is it possible?


Solution

  • Until Amazon allow a custom status code from S3, here is a workaround using nginx.

    We watch for the existence of a specific file, that acts as a "ON switch" for maintenance mode. If found, we proxy_pass requests to S3 - The trick is to return 503 but redirect processing of 503 status codes to a nginx "named location".

    Example nginx conf file (just the relevant bits shown):

    server {
    
        ...
    
        # Redirect processing of 503 status codes to a nginx "named location".
        error_page 503 @maintenance;
    
        # "Maintenance Mode" is off by default - Use a nginx variable to track state.
        set $maintenance off;
    
        # Switch on "Maintenance Mode" if a certain file exists.
        if (-f /var/www/app/maintenanceON) {
            set $maintenance on;
        }
    
        if ($maintenance = on) {
            # For Maintenance mode Google recommend using status code: "503 Service unavailable".
            return 503;
        }
    
        ...
    
        location @maintenance {
            # Redirect the request to a static maintenance page hosted in Amazon S3.
            # Note: Use proxy_pass instead of rewrite so we keep the 503 code (otherwise nginx serves a 302 code)
            rewrite ^(.*)$ /index.html break;
            proxy_pass http://bucketname.s3-website-us-east-1.amazonaws.com;
        }
    }