【问题标题】:Serve both static website & SPA (node.js) with NGINX使用 NGINX 为静态网站和 SPA (node.js) 提供服务
【发布时间】:2023-03-25 01:58:01
【问题描述】:

我需要一种使用 NGINX 为静态 html 网站和 SPA 提供服务的方法。

所以,如果有合适的静态 html 路由,它应该由 NGINX 提供,任何其他路由都应该由 node.js 网络服务器提供。

例如

https://website.com/about -> 由 NGINX 提供服务,因为有 about.html https://website.com/register -> 由 node.js 提供服务,因为该路由没有合适的静态页面(没有 register.html)。

我创建了以下配置,但它似乎无法正常工作。

upstream backend {
    server localhost:8080;
}

server {
    listen 80;
    server_name website.com www.website.com;

    root /var/www/website.com;

    location = / {
        try_files /index.html =404;
    }

    location = /index {
        return 404;
    }

    location / {
        try_files $uri/index.html =404 @backend;
    }

    location @backend {
        proxy_pass http://backend;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
        proxy_redirect off;
    }
}

【问题讨论】:

    标签: nginx


    【解决方案1】:

    您的配置可能会简化为:

    root /var/www/example.com;
    index index.html;
    
    location / {
        try_files $uri $uri/ @backend;
    }
    
    location @backend {
        ...
    }
    

    【讨论】:

    • 这个答案能解决问题吗?听起来你只是在简化他的配置文件。
    【解决方案2】:

    你可以试试

    location / {
        try_files $uri $uri.html $uri/ @backend;
    }
    

    为你分解。 try_files 指令

    按指定顺序检查文件是否存在,并使用第一个找到的文件进行请求处理;

    所以

    $uri - 查找路径中定义的确切文件。对css、图片、js等静态文件很有用。

    $uri.html 查找带有.html 扩展名的确切文件。这会得到你的about.html

    $uri/ - 查找它是一个目录,然后使用index 指令查找indexindex.html

    @backend - 发送到代理应用程序将负责返回 404

    【讨论】:

      猜你喜欢
      • 2019-06-24
      • 2010-12-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多