Search code examples
htmlcssdjangoamazon-s3font-awesome

Font-awesome Icons not loading after connecting to AWS


I am doing a project for developing a website. I chose Django for my backend. I have uploaded my static files on Amazon s3 bucket. All my CSS files and images and every static file are loading except the icons from font-awesome. I tried using their CDN. Yet no result.

  <link href="{% static 'vendor/fontawesome-free/css/all.min.css' %}" rel="stylesheet">
  <link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">

I see no results whatsoever. The URL of my website: https://fine-arts-club.herokuapp.com/


Solution

  • This is usually caused by improperly configured CORS handling.

    Open your browser developer tools. If there is an error saying that Font Awesome could not be loaded because it is blocked by CORS policy, this is the reason.

    To solve this you need to set the access-control-allow-origin HTTP header.

    Setting the value to * will allow any domain.

    access-control-allow-origin: *
    

    You can set the Header value to a specific domain. This is usually the best option for files hosted for a specific site.

    access-control-allow-origin: https://www.your-domain.com
    

    There are two ways to set the CORS header. You can create a policy in your S3 bucket or you can moddify the header using a Lambda@Edge function.

    S3 Configuration

    How to add CORS Documentation

    CORS Configuration Documentation

    <CORSConfiguration>
     <CORSRule>
       <AllowedOrigin>*</AllowedOrigin>
       <AllowedMethod>GET</AllowedMethod>
       <AllowedHeader>https://www.your-domain.com</AllowedHeader>
     </CORSRule>
    </CORSConfiguration>
    

    Lambda@Edge Function

    You can also add the access-control-allow-origin HTTP header using a Lambda@Edge function. It is probably overkill for what you need, but it can be helpful if have a more complex setup.

    To do this you need to create a Lambda function at US-East-1.

    An example of the code you would use would be something like this...

    exports.handler = async (event, context) => {
        const request = event.Records[0].cf.request;
        const response = event.Records[0].cf.response;
    
        // Add logic here
        let cors = "something";
    
        response.headers['access-control-allow-origin'] = [{ key: 'Access-Control-Allow-Origin', value: cors }];
    
        return response;
    };
    

    Once you have created the Lambda function you can add hook it into your CloudFront distribution by editing a behavior and adding your function to Lambda Function Associations as either "Viewer Response" or Origin Response".

    I would recommend using the S3 method for almost all situations.