Nginx 无法加载 tomcat 服务器的 css、js 和 png

Nginx 无法加载 tomcat 服务器的 css、js 和 png

我正在尝试在单个 AWS EC2 实例上部署 tomcat 和 Nginx 服务器。我有 3 个实例,每个实例上我都想部署 Nginx 和 Tomcat 服务器。以下是我的配置文件

/etc/nginx/nginx.conf

user www-data;
worker_processes auto;
pid /run/nginx.pid;
include /etc/nginx/modules-enabled/*.conf;

events {
        worker_connections 768;
        # multi_accept on;
}

http {

        ##
        # Basic Settings
        ##

        sendfile on;
        tcp_nopush on;
        tcp_nodelay on;
        keepalive_timeout 65;
        types_hash_max_size 2048;
        # server_tokens off;

        # server_names_hash_bucket_size 64;
        # server_name_in_redirect off;

        include /etc/nginx/mime.types;
        default_type application/octet-stream;

        ##
        # SSL Settings
        ##

        ssl_protocols TLSv1 TLSv1.1 TLSv1.2; # Dropping SSLv3, ref: POODLE
        ssl_prefer_server_ciphers on;

        ##
        # Logging Settings
        ##

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

        ##
        # Gzip Settings
        ##

        gzip on;

        # gzip_vary on;
        # gzip_proxied any;
        # gzip_comp_level 6;
        # gzip_buffers 16 8k;
        # gzip_http_version 1.1;
        # gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;

        ##
        # Virtual Host Configs
        ##

        include /etc/nginx/conf.d/*.conf;
}"

/etc/nginx/conf.d/application.conf

server {
    listen         80 default_server;
    listen         [::]:80 default_server;
    server_name    localhost;
    root           /var/lib/tomcat9/webapps/ROOT;
    index          deploy.html;
    location /admin {
                try_files $uri $uri/ /deploy.html;
        }
    location /admin/admin-portal {
        alias /opt/tomcat/webapps/ROOT/;
        rewrite /admin-portal/(.*) /$1  break;
        proxy_set_header X-Forwarded-Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-Server $host;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_pass http://localhost:8080/;
        }
    location ~ \.css {
           add_header  Content-Type    text/css;
        }
    location ~ \.js {
            add_header  Content-Type    application/x-javascript;
        }

我的目标是,当我点击 http://IP/ 或 HTTP://IP/admin 时,它应该重定向到 deploy.html ,而当我点击 HTTP://IP/admin/admi-portal 时,它应该打开 tomcat 服务器

注意:我在两种情况下都成功了,除了当我点击 HTTP://IP/admin/admi-portal 时,它只打开 HTML 页面和 CSS/png/js 文件,出现 404:未找到错误

/opt/tomcat/webapps/ROOT/这是所有 tomcat 静态文件 CSS/js/png 等的文件路径

谁能帮我这个?

答案1

在这种情况下,由于 nginx 位置选择算法的工作方式,带有前缀的 CSS/JS 文件的请求/admin/portal/仍然由块提供。location ~ \.css

如果您想阻止正则表达式匹配任何具有/admin/admin-portal前缀的内容,那么您需要使用:

location ^~ /admin/admin-portal {
    ...
}

相关内容