2

I have configured nginx to proxy the request that comes to the port 8000, to route to a different ip. In the configuration i also add Access-control-Allow-Origin header. This works fine if server is responding with 2xx response codes. But if server responds with 4xx response codes, It does not include the header mentioned below

server {
listen *:8000;

ssl                     on;
ssl_certificate         /etc/nginx/ssl/axis.crt;
ssl_certificate_key     /etc/nginx/ssl/axisPrivate.key;
server_name             website.com;
ssl_protocols           SSLv2 SSLv3 TLSv1;
ssl_ciphers             ALL:!ADH:!EXPORT56:RC4+RSA:+HIGH:+MEDIUM:+LOW:+SSLv3:+EXP;
access_log /var/log/nginx/nginx.vhost.access.log;
error_log /var/log/nginx/nginx.vhost.error.log;

location / {
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_pass https://api;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_ssl_session_reuse off;
    proxy_set_header Host $http_host;

    proxy_redirect off;
    proxy_intercept_errors off;  
# Simple requests
    if ($request_method ~* "(GET|POST|PUT)") {
      add_header "Access-Control-Allow-Origin" "https://website.com";
    }

    # Preflighted requests
    if ($request_method = OPTIONS ) {
      add_header "Access-Control-Allow-Origin"  "https://website.com";
      add_header "Access-Control-Allow-Methods" "GET,PUT,POST, OPTIONS, HEAD";
      add_header "Access-Control-Allow-Headers" "Authorization, Origin, X-Requested-With, Content-Type, Accept,access-control-allow-methods,access-control-allow-origin";
      return 200;
    }

}
}

upstream api {
 server ip:port;
}

Since the header is missing the Access-Control-Allow-Origin, browser is blocking any action to be performed on the response.

Error log in the browser :

POST https://website.com:8000/employee 409 ()
EmployeeRegistration:1 Failed to load https://website.com:8000/employee: No 'Access-Control-Allow-Origin' header is present on the requested resource. 
Origin 'https://website.com' is therefore not allowed access. The response had HTTP status code 409.
Sam
  • 123
  • 4

1 Answers1

3

This is the intended behavior:

Syntax: add_header name value [always];

Default: — Context: http, server, location, if in location

Adds the specified field to a response header provided that the response code equals 200, 201 (1.3.10), 204, 206, 301, 302, 303, 304, 307 (1.1.16, 1.0.13), or 308 (1.13.0). The value can contain variables.

There could be several add_header directives. These directives are inherited from the previous level if and only if there are no add_header directives defined on the current level.

If the always parameter is specified (1.7.5), the header field will be added regardless of the response code.

You need the always keyword in the add_header directive.

drookie
  • 8,051
  • 1
  • 17
  • 27