Nginx – CORS configuration that allows files to be served to localhost

corsnginxUbuntu

Here is my current nginx configuration file:

server {
listen 80 default_server;
listen [::]:80 default_server;

root /var/www/html;

# Add index.php to the list if you are using PHP
index index.html index.htm index.nginx-debian.html;

server_name _;

location / {
    # First attempt to serve request as file, then
    # as directory, then fall back to displaying a 404.
    try_files $uri $uri/ /index.html;
}

location /home {

    if ($request_method = 'OPTIONS') {
        add_header 'Access-Control-Allow-Origin' '*';
        add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';

        add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';

        add_header 'Access-Control-Max-Age' 1728000;
        add_header 'Content-Type' 'text/plain charset=UTF-8';
        add_header 'Content-Length' 0;
        return 204;
    }
    if ($request_method = 'POST') {
        add_header 'Access-Control-Allow-Origin' '*';
        add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
        add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';
    }
    if ($request_method = 'GET') {
        add_header 'Access-Control-Allow-Origin' '*';
        add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
        add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';
    }

}}

I currently have it set up so it works as expected on the server. Files are served up correctly when referencing them from index.html and no CORS errors are present.

The same index.html is use when doing development on a local web server (http://localhost:4200).

The errors look like this:

Access to Imported resource at 'http://sub.domain.io//public/bower_components/polymer/polymer.html' from origin 'http:/sub.domain.io' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access.

I already attempted to put "Access-Control-Allow-Origin *;" in the server {} instead of location.

Any idea on how to get this done?

Best Answer

perhaps, the url that your are specifying under location is not the location you are trying to access. your error is related to path http://sub.domain.io//public/bower_components/polymer/polymer.html

try adding a section for location /public with the add_header 'Access-Control-Allow-Origin' '*';