All Linux HowTo's Security HowTo's

Enable CORS With NginX

Like happens so often, the notes and comments you found in forums don’t quiet work how you expected. In this article i demonstrate how to enable CORS on NginX and show you how to test it. You’ll see a working example.

There are reasons you can’t do this without modifications – it’s a security risk. It’s a risk that can be mitigated by limitations that are not covered here.

We’re using NginX version 1.12 on CentOS 7.

First we have our NginX vhost. I’m using an example hostname of “www.example.com.au”. For the record, the vhost file is located in (and called) “/etc/nginx/conf.d/www.example.com.au.conf”.

server {
        listen 80;
        server_name www.example.com.au;

        access_log   /var/log/nginx/www.example.com.au.access.log;
        error_log    /var/log/nginx/www.example.com.au.error.log;

        root /var/www/www.example.com.au;
        index index.html;

        location / {
                add_header 'Access-Control-Allow-Origin' '*';
                add_header 'Access-Control-Allow-Credentials' 'true';
                add_header 'Access-Control-Allow-Headers' 'Content-Type,Accept';
                add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS, PUT, DELETE';
        }
}

The following is how to confirm it’s working:

curl -H "Access-Control-Request-Method: GET" -H "Origin: https://www.google.com.au" --head http://www.example.com.au

You will get some output like the following. Make sure you got the source and destination right in the above command and verify it with the output. For instance, i said above that we’re using NginX 1.12 and you can see in the second line below we’re hitting that server.

HTTP/1.1 200 OK
Server: nginx/1.12.2
Date: Wed, 29 Aug 2018 06:21:07 GMT
Content-Type: text/html
Content-Length: 5
Last-Modified: Wed, 29 Aug 2018 06:13:09 GMT
Connection: keep-alive
ETag: "5b863975-5"
Access-Control-Allow-Origin: *
Access-Control-Allow-Credentials: true
Access-Control-Allow-Headers: Content-Type,Accept
Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE
Accept-Ranges: bytes

If you don’t get the “Access-Control-Allow-Origin” output, you’ve done something wrong.

Similar Posts:

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.