SSL을 사용하는 Tomcat에 대한 nginx 프록시

Jan 29 2021

실수로 stackoverflow에 게시했습니다 (https://stackoverflow.com/questions/65942820/nginx-proxy-to-tomcat) 그리고 몇 가지 해결책을 찾기 위해 여기에 넣습니다.

수십 개의 자습서를 살펴 봤지만 다음을 파악할 수 없습니다 (아주 기본이어야 함).

컴파일 된 vue 애플리케이션이 /var/www/mydomain.com에 있고 정적 콘텐츠로 공유되기를 원합니다.

내 백엔드는 / api / something ... URL의 공개 API를 사용하여 tomcat에 의해 8080에서 실행됩니다. URL은 "api"부분을 포함하여 하드 코딩됩니다.

mydomain.com/api/something ... tomcat에 대한 요청을 프록시하고 나머지는 /var/www/mydomain.com에서 정적으로 제공되도록 nginx를 구성하고 싶습니다. 모든 것이 SSL을 통해 제공되었습니다.

나는 말 그대로 다른 것이 필요하지 않습니다.

이를 달성하기 위해 nginx 및 tomcat을 구성하는 데 도움을 줄 수 있습니까? 감사합니다!

nginx 구성 /etc/nginx/sites-available/mydomain.com

upstream tomcat {
    server 127.0.0.1:8080 fail_timeout=0;
}

server {
        listen 443 ssl default_server;
        #listen [::]:443 ssl default_server;

        root /var/www/mydomain.com;
        index index.html index.htm index.nginx-debian.html;

       server_name _ mydomain.com www.mydomain.com;

        location /api/ {
                include proxy_params;
                proxy_set_header Host $server_name; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
                proxy_set_header X-Forwarded-Proto $scheme; proxy_pass http://tomcat; } location / { try_files $uri $uri/ /index.html; } ssl_certificate /etc/letsencrypt/live/www.mydomain.com/fullchain.pem; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/www.mydomain.com/privkey.pem; # managed by Certbot } server { if ($host = www.mydomain.com) {
        return 301 https://$host$request_uri;
    } # managed by Certbot


    if ($host = mydomain.com) { return 301 https://$host$request_uri;
    } # managed by Certbot


       listen 80 default_server;
        listen [::]:80 default_server;

       server_name _ mydomain.com www.mydomain.com;
   return 404; # managed by Certbot
}

(1) Alternative location block I'm experimenting with

        location /api/ {
                proxy_set_header Host $host;
                proxy_set_header X-Real-IP $remote_addr;
                proxy_set_header X-Forwarded-Proto https;
                proxy_pass http://localhost:8080/api/;
        }

(2) Alternative block suggested by Praveen Premaratne.

This way I get "GET /api/docs HTTP/1.0" 302 - and static files work as well. Going to /api/docs makes redirect to domain:8443/api/docs where I get ERR_CONNECTION_REFUSED.

        location /api/ {
                include proxy_params;
                proxy_pass http://tomcat;
        }

        location / {
                try_files $uri $uri/ /index.html;
        }

(3) Alternative using subdomain.

I was able to create subdomain api.mydomain.com and configure nginx to go to index page from there (adding following block). No idea how to do the proxing afterwards.

server {
        listen 443 ssl;

        root /var/www/www.mydomain.com; <- redundand I guess?
        index index.html index.htm index.nginx-debian.html; <- redundand I guess?

        server_name api.mydomain.com

        ssl_certificate /etc/letsencrypt/live/www.mydomain.com/fullchain.pem; # managed by Certbot
        ssl_certificate_key /etc/letsencrypt/live/www.mydomain.com/privkey.pem; # managed by Certbot
}

Tomcat config server.xml

<Connector port="8080" protocol="HTTP/1.1"
               connectionTimeout="20000"
               address="127.0.0.1"
               redirectPort="8443" />
<Engine name="Catalina" defaultHost="localhost">
   ...
   <Host name="localhost"  appBase="webapps"
         unpackWARs="true" autoDeploy="true">
      
      <Valve className="org.apache.catalina.valves.AccessLogValve" 
         directory="logs"
         prefix="localhost_access_log" suffix=".txt"
         requestAttributesEnabled="true"
         pattern="%h %l %u %t &quot;%r&quot; %s %b" />
        
      <Valve className="org.apache.catalina.valves.RemoteIpValve"
         protocolHeader="X-Forwarded-Proto" /> 
   ...    

Current situation is that when I go to mydomain.com/api/docs where swagger should be running, I get redirected back to mydomain.com or get 500 or 502 error.

답변

1 TomášLeitl Feb 01 2021 at 01:45

Ok, so with help of @Praveen Premaratne and @Piotr P. Karwasz and this article I came up with following configuration:

don't put in lines with "# managed by Certbot", those are created by certbot, check https://www.digitalocean.com/community/tutorials/how-to-secure-nginx-with-let-s-encrypt-on-ubuntu-18-04

etc/nginx/sites-available/mydomain.com

server {
    server_name    mydomain.com www.mydomain.com;

    root /var/www/mydomain.com;
    index index.html;

    access_log /var/log/nginx/mydomain-access.log;
    error_log /var/log/nginx/mydomain-error.log;

    location / {
        try_files $uri $uri/ /index.html;
    }

    listen 443 ssl; # managed by Certbot
    ssl_certificate /etc/letsencrypt/live/www.mydomain.com/fullchain.pem; # managed by Certbot
    ssl_certificate_key /etc/letsencrypt/live/www.mydomain.com/privkey.pem; # managed by Certbot
    include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot
}

server {
    if ($host = www.mydomain.com) { return 301 https://$host$request_uri; } # managed by Certbot if ($host = mydomain.com) {
        return 301 https://$host$request_uri;
    } # managed by Certbot


    server_name    mydomain.com www.mydomain.com;
    listen 80;
    return 404; # managed by Certbot
}

/etc/nginx/sites-available/api.mydomain.com

server {
    server_name    api.mydomain.com;

    access_log /var/log/nginx/api-mydomain-access.log;
    error_log /var/log/nginx/api-mydomain-error.log;

    location / {
        proxy_set_header Host $http_host; proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Host $http_host;
        proxy_set_header X-Forwarded-Proto $scheme; proxy_pass http://127.0.0.1:8080; } listen 443 ssl; # managed by Certbot ssl_certificate /etc/letsencrypt/live/www.mydomain.com/fullchain.pem; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/www.mydomain.com/privkey.pem; # managed by Certbot include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot } server { if ($host = api.mydomain.com) {
        return 301 https://$host$request_uri;
    } # managed by Certbot

    server_name    api.mydomain.com;
    listen 80;
    return 404; # managed by Certbot
}

Tomcat server.xml

<Service name="Catalina">
<Connector port="8080" protocol="HTTP/1.1"
    connectionTimeout="20000"
    address="127.0.0.1"
    proxyName="api.mydomain.com"
    proxyPort="80"/>

<Engine name="Catalina" defaultHost="localhost">

    <Realm className="org.apache.catalina.realm.LockOutRealm">
    ...
    </Realm>

    <Host name="localhost"  appBase="webapps"
        unpackWARs="true" autoDeploy="true">

        <Valve className="org.apache.catalina.valves.RemoteIpValve"
            remoteIpHeader="x-forwarded-for"
            proxiesHeader="x-forwarded-by"
            protocolHeader="x-forwarded-proto" />

        <Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs"
            prefix="localhost_access_log" suffix=".txt"
            pattern="%h %l %u %t %r %s %b" />

  </Host>
</Engine>
fuero Jan 29 2021 at 20:01

Try this:

location / {
        try_files $uri @backend;
}
location @backend {
        include proxy_params;
        proxy_pass http://tomcat;
}
PraveenPremaratne Jan 29 2021 at 23:22

If I were to do this using the subdomains approach here's how I would do it.

  • Create an Nginx configuration file for the backend API
  • Create an Nginx configuration file for the static web content

Static HTML Nginx file mydomain.com.nginx

server {
    server_name    mydomain.com;

    root /var/www/mydomain.com;
    index index.html;

    access_log /var/log/nginx/mydomain-access.log;
    error_log /var/log/nginx/mydomain-error.log;

    location / {
        try_files $uri $uri/ /index.html;
    }

    listen 443 ssl; # managed by Certbot
    ssl_certificate /etc/letsencrypt/live/www.mydomain.com/fullchain.pem; # managed by Certbot
    ssl_certificate_key /etc/letsencrypt/live/www.mydomain.com/privkey.pem; # managed by Certbot
    include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot

}
server {
    if ($host = mydomain.com) { return 301 https://$host$request_uri;
    } # managed by Certbot


    listen         80;
    server_name    mydomain.com;
    return 404; # managed by Certbot


}

API Nginx config file api.mydomain.com.nginx

server {
    server_name    api.mydomain.com;

    access_log /var/log/nginx/api-mydomain-access.log;
    error_log /var/log/nginx/api-mydomain-error.log;

    location / {
        proxy_set_header X-Forwarded-Host $host:$server_port; proxy_set_header X-Forwarded-Server $host;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_pass http://127.0.0.1:8080; proxy_redirect off; } listen 443 ssl; # managed by Certbot ssl_certificate /etc/letsencrypt/live/api.mydomain.com/fullchain.pem; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/api.mydomain.com/privkey.pem; # managed by Certbot include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot } server { if ($host = api.mydomain.com) {
        return 301 https://$host$request_uri;
    } # managed by Certbot


    listen         80;
    server_name    app.mydomain.com;
    return 404; # managed by Certbot


}

You can add these to the /etc/nginx/site-available/ directory and enable them.

Ps: I would remove the SSL stuff and run Certbot to update them since you've to issue a new certificate for the app.mydomain.com, so it would just update the files itself