Nginx solution to web static files are blocked by CORS policy: No 'Access-Control-Allow-Origin' header

If a website is trying to access web static files from different URL domain, broken web assets and the following error will occur:

Access to Font at '' from origin '' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin '' is therefore not allowed access.

The following Nginx codes will add HTML header responses Access-Control-Allow-Origin: * and Cache-Control: public web static files of domain to let other domains access these web static files without issues:

location / {
  location ~* ^.+\.(?:css|cur|json|js|jpe?g|gif|htc|ico|png|txt|otf|ttf|eot|woff|svg|webp|webm|zip|gz|tar|rar)$ {
    set $test_http_origin a;
    if ($http_origin != "") {
      set $test_http_origin x;
    if ($http_origin != "${scheme}://${host}") {
      set $test_http_origin "${test_http_origin}x";
    if ($test_http_origin = xx) {
      add_header "Access-Control-Allow-Origin" "*";
    access_log off;
    expires 30d;
    ## No need to bleed constant updates. Send the all shebang in one
    ## fell swoop.
    tcp_nodelay off;
    ## Set the OS file cache.
    open_file_cache max=3000 inactive=120s;
    open_file_cache_valid 45s;
    open_file_cache_min_uses 2;
    open_file_cache_errors off;
    try_files $uri $uri/ @cache;

In this article, you will find the complete Nginx configuration or shall we say continuation to follow the named location @cache from above Nginx codes.


Add new comment

Restricted HTML

  • Allowed HTML tags: <a href hreflang> <em> <strong> <cite> <blockquote cite> <code> <ul type> <ol start type> <li> <dl> <dt> <dd> <h2 id> <h3 id> <h4 id> <h5 id> <h6 id>
  • Lines and paragraphs break automatically.