Enable AWS CDN with Custom Origin option
- Open CloudFront in AWS Management Console. If you don’t have AWS account, create it at https://aws.amazon.com
- Click ‘Create Distribution‘.
- Select the option ‘Download‘. Click Continue.
- Set ‘Origin Domain Name‘ to your web server domain.
- Set ‘Forward Query Strings‘ option to ‘Yes‘. This is because tornado can generate a hash code for each static resource, for best cache performance.
- Set other options accordingly. Click ‘Create Distribution‘. Your CDN distribution is ready to use, once its state becomes Enabled.
- Record the Domain Name field. We will use it soon. It normally looks like d1234.cloudfront.net
Enable it easily with python tornado
- First, apparently we don’t want to use CDN in dev mode. To easily switch between dev and production mode, customize your base RequestHandler like below
# replace it with your own CDN domain name
# replace it with your custom logics here. Here by default we return False
def static_url(self, path, include_host=None, **kwargs):
relative_url = super(BaseHandler, self).static_url(path, include_host=False, **kwargs)
return '//' + self.get_cdn_host_name() + relative_url
return super(BaseHandler, self).static_url(path, include_host=include_host, **kwargs)
We override the static_url method here. Custom the is_cdn_enabled method. Let it depends on the production mode. Then it will automatically employ CDN in production deployment. Enjoy coding!