【问题标题】:Nginx location regex not working for sub pagesNginx 位置正则表达式不适用于子页面
【发布时间】:2023-03-18 00:58:01
【问题描述】:

我有两个 react 应用程序,一个在“/home/user/www”,一个在“/home/user/builds/checkout”。我想要任何以“/ checkout”开头的网址,例如。 '/checkout/complete'、'/checkout/error' 以使用该应用程序。我的 Nginx 配置文件中有以下设置:

    root /home/user/www;
    index index.html index.htm;        
    location / {
      if (!-e $request_filename){
        rewrite ^(.*)$ /index.html break;
      }
    }         

    location ~ ^/checkout?(.*)$ {
            allow all;
            root /home/user/builds;
     if (!-e $request_filename){
        rewrite ^(.*)$ /index.html break;
      }
            try_files $uri $uri/index.html =404;
     }

    location ~ ^.+\..+$ {
            try_files $uri =404;
    }

转到 url '/checkout' 工作正常,但任何其他以 '/checkout' 开头的 url,如 '/checkout/complete' 和 'checkout/error' 都只是返回 404 页面。

【问题讨论】:

    标签: nginx nginx-config nginx-location


    【解决方案1】:

    您的配置看起来太复杂了。你可以试试这个吗?

    root /home/user/www;
    index index.html index.htm;        
    location / {
        try_files $uri /index.html;
    }         
    
    location /checkout/ {
        root /home/user/builds;
        try_files $uri $uri/ /checkout/index.html;
    }
    

    如果/checkout URI 不会将您重定向到/checkout/,请添加:

    location = /checkout {
        return 301 /checkout/;
    }
    

    【讨论】:

    • 这会将所有“/checkout”页面指向应用程序,但现在所有包含的 .css 和 .js 文件(存储在“/home/user/builds/checkout”中) 404 失败。
    • 如果应用请求其资产时没有/checkout URI 前缀,则应在应用级别进行修复。
    • 阅读this评论。
    • 应用程序实际上是使用 /checkout URI 请求资产,因为我在路由器基本名称中设置了它
    • 这真的很奇怪。当一个请求让我们说/checkout/css/style.css 时,这个文件应该被搜索为/home/user/builds/checkout/css/style.css。这样对吗?您的服务器块中的任何其他位置可以拦截请求吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-11
    • 2017-04-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多