-->

Running a Spring Boot app behind nginx

2020-07-05 06:30发布

问题:

I have a Spring Boot + MVC app up and running on my server and it's bound to http://localhost:8000.

There is an nginx proxy (or is it a reverse proxy, not sure about the name) that listens to the outside world on ports 80 and 443. The root ( / ) will resolve correctly, but anything under it will not resolve and results in a 404 error ( /someControllerName/action, /images/, /css/ ).

I have this as my configuration:

upstream jetty {
        server localhost:8000;
}

server {
        listen       80;
        server_name  domain.com;
        return       301 http://www.domain.com$request_uri;
}

server {
        listen       443;
        server_name  domain.com;
        ssl_certificate /etc/nginx/ssl/ssl.crt;
        ssl_certificate_key     /etc/nginx/ssl/ssl.key;
        return       301 https://www.domain.com$request_uri;
}

server {
        listen 80 default_server;
        listen 443 ssl;

        root /usr/share/nginx/html;
        index index.html index.htm;

        server_name www.domain.com localhost;

        #ssl    on;
        ssl_certificate /etc/nginx/ssl/ssl-unified.crt;
        ssl_certificate_key     /etc/nginx/ssl/ssl.key;

        location / {
                # First attempt to serve request as file, then
                # as directory, then fall back to displaying a 404.
                # Uncomment to enable naxsi on this location
                # include /etc/nginx/naxsi.rules
                proxy_pass              $scheme://jetty/$request_uri;
                proxy_redirect  off;
                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;
                try_files $uri $uri/ =404;
        }
}

Any help is very much appreciated.

回答1:

You can't combine proxy_pass with try_files in the way that you have attempted. As the comment in your configuration describes, the try_files directive causes nginx to look for a file that matches the URI and then look for a directory that matches the URI. If it doesn't find either, it responds with a 404. You can read more about try_files in the nginx documentation.

It's not clear from your question that you need to use try_files at all so the simplest way to fix your configuration is to remove the try_files line.