How to add CORS (cross origin policy) to all domains in NGINX?

How to add CORS (cross origin policy) to all domains in NGINX?

August 13, 2026 · Illustrated author avatarBy Stefan Bogdanescu
How to add CORS (cross origin policy) to all domains in NGINX?

Allowing Cross Origin Access for All Domains via NGINX

When it comes to serving static files from a subdomain or CDN in a Magento 2 setup, cross origin access is crucial for seamless integration with your front-end application. In this post, we’ll guide you through enabling CORS (Cross-Origin Resource Sharing) for all domains using the NGINX web server.

Understanding Your Current Configuration

You’re on the right track with your current NGINX configuration:

location /cdn-directory/ {

    location ~* \.(ico|jpg|jpeg|png|gif|svg|js|css|swf|eot|ttf|otf|woff|woff2|zip|gz|gzip|bz2|csv|xml)$ {
        add_header Cache-Control "public";
        add_header X-Frame-Options "ALLOW-FROM *";
        expires +1y;
    }

}

This setup serves static files from the /cdn-directory location and expires them after one year for better caching. The X-Frame-Options header is used to control whether your content can be framed by other websites.

Enabling CORS for All Domains

To allow cross origin access for all domains, you need to modify the add_header X-Frame-Options line in your configuration:

location /cdn-directory/ {

    location ~* \.(ico|jpg|jpeg|png|gif|svg|js|css|swf|eot|ttf|otf|woff|woff2|zip|gz|gzip|bz2|csv|xml)$ {
        add_header Cache-Control "public";
        add_header Access-Control-Allow-Origin "*";
        expires +1y;
    }

}

We’ve replaced X-Frame-Options with the Access-Control-Allow-Origin header and set its value to *. This tells the browser that your static files can be accessed from any origin, effectively allowing all domains.

Why We Prefer Access-Control-Allow-Origin

While X-Frame-Options is used to prevent clickjacking attacks by controlling how your content can be framed, it’s not the best header for enabling CORS. The more appropriate and widely-supported header for this purpose is Access-Control-Allow-Origin.

Conclusion

In conclusion, enabling cross origin access for all domains in NGINX involves setting the Access-Control-Allow-Origin header to * within your static files location block. This simple modification allows your static content to be accessed from any domain.

Remember that while this configuration provides wide accessibility, it’s important to consider security implications and potential vulnerabilities when allowing unrestricted access to your resources. Always ensure you have proper measures in place to protect sensitive data.

For more advanced configurations and best practices on serving static files in Magento 2, I recommend checking out the Laravel Company Blog. They provide excellent insights into optimizing performance and security for e-commerce platforms like Magento.

Magento 2 Cache Themes Configuration

Our network