T
T
tamtakoe2015-02-01 05:41:11
Nginx
tamtakoe, 2015-02-01 05:41:11

What should be the structure of nginx.conf with basic authorization and cors?

The application uses cross-domain requests and basic authorization. A config like this comes to mind:

server {
    location / {
        #CORS
        if ($request_method = OPTIONS ) {
            add_header Access-Control-Allow-Origin "http://localhost"; # <- needs to be updated
            add_header Access-Control-Allow-Methods "GET, OPTIONS";
            add_header Access-Control-Allow-Headers "Authorization";   # <- You may not need this...it's for Basic Auth
            add_header Access-Control-Allow-Credentials "true";        # <- Basic Auth stuff, again
            add_header Content-Length 0;
            add_header Content-Type text/plain;
            return 200;
        }


        #Authentification
        satisfy any;

        allow 123.456.789.001;
        allow 123.456.789.002;
        deny  all;
        
        auth_basic           "Admin section";
        auth_basic_user_file .htpasswd;


        #Routing
        location ~ ^/(images|javascripts|stylesheets|system)/  {
            root /some/directory/for/rails/app/public;
            expires max;
            break;
        }

        location ... {
            ...
        }
    }
}

I don't like having to wrap everything in `location /`. How to do it right? Can you share your configs?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Guz, 2015-10-24
@aguz

Perhaps for the sake of history I will leave an example.
Headers will be Access-Control-Allow-*required in all types of requests. Therefore, they do not need to be segmented as on enable-cors.org
The need for a condition if ($request_method)at the location level, and not server, was related to the peculiarities of nginx.

server {

    #Authentification
    satisfy any;

    allow 123.456.789.001;
    allow 123.456.789.002;
    deny  all;
        
    auth_basic           "Admin section";
    auth_basic_user_file .htpasswd;

    #CORS
    add_header Access-Control-Allow-Origin "http://localhost"; # <- needs to be updated
    add_header Access-Control-Allow-Methods "GET, OPTIONS"; # 
    add_header Access-Control-Allow-Headers "Authorization";
    add_header Access-Control-Allow-Credentials "true"; 

    location / {
        if ($request_method = OPTIONS ) { # <- because if ($request_method) doesn't work on server level
            add_header Content-Length 0;
            add_header Content-Type text/plain;
            return 200;
        }
    }

    #Routing
    location ~ ^/(images|javascripts|stylesheets|system)/  {
         root /some/directory/for/rails/app/public;
         expires max;
        break;
    }

    location ... {
        ...
    }

}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question