bartvanremortele
9/10/2015 - 3:39 PM

Nginx vhost configuration for proxying requests to an API running on a different port. Easy to avoid CORS / JSONP

Nginx vhost configuration for proxying requests to an API running on a different port. Easy to avoid CORS / JSONP

upstream api_node_js {
    server 127.0.0.1:8080;
}

server {
	listen 80 default_server;
	listen [::]:80 default_server ipv6only=on;

    root /var/www/my-kickass-domain/public_html;
    index index.html index.htm;

	# Make site accessible from http://localhost/
	server_name my.kickass.domain;

	location / {
		# First attempt to serve request as file, then
		# as directory, then fall back to redirecting the request to the SPA
		try_files $uri $uri/ /index.html;
		# Uncomment to enable naxsi on this location
		# include /etc/nginx/naxsi.rules
	}

    location /api {
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $host:$server_port;
        proxy_set_header X-NginX-Proxy true;

        # rewrite ^/api/?(.*) /$1 break;

        proxy_pass http://api_node_js;
        proxy_redirect off;
    }

    location /auth {
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $http_host;
        proxy_set_header X-NginX-Proxy true;

        # rewrite ^/auth/?(.*) /$1 break;

        proxy_pass http://api_node_js;
        proxy_redirect off;
    }
}