如何配置 nginx 为单页应用程序的其他所有内容提供静态文件和 index.html

Der*_*rek 2 nginx single-page-application

我正在构建一个使用 nginx 作为 Web 服务器来提供静态文件的 SPA。我需要一种方法来为根 index.html 文件提供一些路由:

  • /温泉/路线
  • /其他/
  • /测试
  • /另一个/

但仍然允许提供静态文件。

我尝试了很多方法,但没有一个成功。

lif*_*foo 8

你应该有一个nginx.conf这样的(我从我的一个旧的角度项目中得到了这个):

server {
    ## Your website name goes here.
    server_name example.com;

    ## Your only path reference.
    root /var/www/example.com/public_html;

    ## This should be in your http block and if it is, it's not needed here.
    index index.html;

    autoindex off;

    location = /favicon.ico {
        log_not_found off;
        access_log off;
    }

    location = /robots.txt {
        allow all;
        log_not_found off;
        access_log off;
    }

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

    location ~* \.(js|css|png|jpg|jpeg|gif|ico)$ {
        expires max;
        log_not_found off;
    }
}
Run Code Online (Sandbox Code Playgroud)

第一条和第二location条规则适用于不需要任何特殊检查并且经常从机器人和浏览器请求的公共文件。

第三条规则表示,如果请求的文件(相对 url)不存在,index.html则将提供该文件。此文件是您的 SPA 的主文件。该break如果该规则的要求相匹配的关键字将停止进程。

最后一条规则是,如果请求的文件以 js、css、png、...(您的静态资产)结尾,它将按原样作为服务器,无需任何重写。通过这种方式,您可以毫无困难地将资产存放在任何目录中。

PS 我也在$locationProvider.html5Mode(true);我的 angular 应用程序中使用了它来获得真实的url,并且它的效果很好。