【问题标题】:nginx location block to match urlnginx 位置块以匹配 url
【发布时间】:2016-08-15 12:00:49
【问题描述】:

我想通过以下方式使用 nginx 路由我的请求

site.com/admin -> admin/index.html
                  admin/js/assets.js // the route locations have individual assets
site.com/112dw -> dist/index.html // alphanumeric regex
                  dist/css/assets.css

我有以下 nginx 配置

server {
    listen 80
    root /usr/share/nginx/html;
    location /admin {
        //alias /usr/share/nginx/html/admin/;
        try_files $uri /admin/index.html; // changed based on answer below
    }
    location ~* /[a-zA-Z0-9].*$ { // rest of the routes
        add_header 'Access-Control-Allow-Origin' '*';
        //alias /usr/share/nginx/html/dist/;
        try_files $uri /dist/index.html;
    }
}

在我将配置更改为使用 try_files 后,我的静态资产没有被提供,因为 HTML 正在搜索上面的路径一目录。谁能指出我正确设置它?

【问题讨论】:

    标签: nginx


    【解决方案1】:

    最简单的方法是使用try_files

    root /usr/share/nginx/html;
    
    location =/admin {
        try_files /admin/index.html =404;
    }
    location ~*^/[a-z0-9]+$ {
        try_files /dist/index.html =404;
    }
    

    【讨论】:

    • 我的静态文件没有被这个方法提供。 html 正在搜索 html/js 而不是 html/dist/js
    • 这需要我为静态文件单独配置所有文件夹吗? html 请求在没有 dist in 请求的情况下发送,因此所有 js 请求都失败了。如果这是一个菜鸟问题,我很抱歉.. 我是 nginx 新手并试图理解配置。
    • @PavanK 您的问题中没有“js”请求,上面的配置仅用于服务您提供的这两种类型的请求。您应该使用完整的要求列表更新您的问题。
    • 第二个位置不起作用。该路由将指向 html 文件夹中的 index.html。位置不变。我仍在尝试配置,但我已经接受了这个答案,因为我至少可以得到一个部分
    • @PavanK 您能否说明site.com/112dw 请求需要如何映射到dist/css/assets.css
    【解决方案2】:

    您可以使用indextry_filesrewrite 指令将请求指向index.html

    您不需要使用正则表达式位置作为默认值。实际上,按照您在问题中定义的方式,从未咨询过 /admin 位置。

    您应该使用root 而不是alias(请参阅this document)。

    有多种解决方案,可能取决于您的资源文件应该如何解决。这种模式可能适合您:

    root /usr/share/nginx/html/dist;
    
    location / {
        try_files $uri /index.html;
    }
    location /admin {
        root /usr/share/nginx/html;
        try_files $uri /admin/index.html;
    }
    

    【讨论】:

    • 我的静态文件没有被这个方法提供。 html 正在搜索 html/js 而不是 html/dist/js
    猜你喜欢
    • 2017-08-11
    • 1970-01-01
    • 2011-07-11
    • 2021-09-05
    • 1970-01-01
    • 2020-03-04
    • 1970-01-01
    • 1970-01-01
    • 2011-06-07
    相关资源
    最近更新 更多