I want to setup an Nginx with this purpose.


  • Serve Angular 2 dist static files from root url: http://example.com -> display the index.html at /home/www/index.html

  • In my Angular2 project, I make some calls locally to /api/some-endpoints both in GET, POST.

  • I want the calls to /api/{ANY-PATH} be redirected as is to a remote private url. I need the call be made with my custom headers (for example form-data or apikey header) AND add another apikey to the request to distant server.

My problem

When making a POST call (from machine where nginx is installed) to /api/document, with form-data values (containing an uploaded file) and my custom header: apikey , 253018b8425f4eb08291a1b68c4bc328

The distant server doesn't seem to receive nor the form-data nor the apikey.

My config

upstream api-server {
    server myprivate-api-server.com:8000;

map $http_apikey $api_route {
    default "error";
    253018b8425f4eb08291a1b68c4bc328 'api-server';

server {
        listen 80;
        index index.html;
        server_name example.com;

        location = /501_apikey.html {
                root /home/www/error_pages;

        location ~ /api/(?<path>.*) {

            if ($request_method = OPTIONS ) {           
                add_header 'Access-Control-Allow-Origin' "$http_origin";
                add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
                add_header 'Access-Control-Allow-Headers' 'apikey';
                return 200;

            if ($api_route = "error"){return 501;}

            set $clientapikey "hW4g5V60UT2O3iQP1PS2g29hKjQ403E5";
            error_page 501 /501_apikey.html;

            add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS, PUT';
            add_header 'Access-Control-Allow-Headers' 'apikey';
            add_header 'clientapikey' $clientapikey;

            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-NginX-Proxy true;    
            proxy_pass http://$api_route/$path$is_args$args;
            proxy_set_header X-Forwarded-For $remote_addr;
            proxy_set_header X-Forwarded-Host $remote_addr;
            proxy_ssl_session_reuse off;
            proxy_set_header Host $http_host;
            add_header 'Access-Control-Allow-Headers' 'apikey';
            proxy_redirect off;

Bonus question

Is my way of adding the client second key valid?

add_header 'clientapikey' $clientapikey;

I will need in the future to create a location for each of my client, each with different clientapikey to identify them on the remote API.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.