Nginx doesn’t pass outer request to localhost

http-status-code-404javajettynginxPROXY

Jetty server runs on localhost:8080 and successfully responses when I make requests via curl (putty):

curl -H "Content-Type: application/json" -X POST -d '{"message":"Hi"}' http://localhost:8080

I have following nginx.conf configuration:

server{
        listen 80;
        server_name 52.27.79.132;
        root /data/www;
        index index.html

        # static files: .png, .css, .js...
        location /static/ {
           root /data/www;
        }

        location ^~/api/*{
            proxy_pass        http://localhost:8080;
            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;
        }

    }

# include /etc/nginx/sites-enabled/*;

Java servlet runs, when jetty server gets request to "/"

Browser successfully returns index.html page, but when javascript makes AJAX-request to 'http://52.27.79.132/api/' I get 404 error

Does anyone know why ?

Best Answer

The regex is not right in your version. However, you don't actually need regex matching in your case, so you can use this version:

location /api {
    proxy_pass        http://localhost:8080;
    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;
}

If you want to use regex for some reason, the first line should look like this:

location ^~ ^/api/.*

The dot means any character and asterisk means repeat 0 or more times.

In your original location line, you repeated / 0 or more times.

Related Topic