【问题标题】:Nginx conf for prerender + reverse proxy to django + serving angular in html5 modeNginx conf 用于预渲染 + django 的反向代理 + 在 html5 模式下提供 Angular
【发布时间】:2016-06-20 20:53:18
【问题描述】:

满口的标题说明了一切:

我们有一个 Angular 前端和一个 Django 后端,提供一个 REST API,该 API 在端点 example.com/api/v1/* 上独立公开

Angular 应用程序在 HTML5 模式下运行,我们希望硬链接到 example.com/foo/bar 以将用户带入处于 foo.bar 状态的应用程序,就好像它是静态页面而不是应用程序状态(其中 foo不是api)。

我们在 nginx 后面运行,我们在 conf 中的基本策略是在^~ /scripts/images 等处定义用于直接提供静态内容的位置,以及一个路由到 django 的^~ /api/* 位置.在此之下,我们有一个 location ~ ^/.+$ 匹配任何上述任何不匹配的路径并“将其发送到 Angular” - 即将我们的索引页面提供给它并将路径附加到基本 url,允许我们的角度路由器处理从那里开始。

这是我们的完整conf:

upstream django {
    server 127.0.0.1:8000 fail_timeout=0;
}

server {
    listen                  80;
    server_name example.com;
    return 301 https://example.com$request_uri;
}

server {
    listen          443;
    server_name example.com;
    client_max_body_size 10M;
    ssl                     on;
    ssl_certificate         /etc/ssl/thawte/example_com.crt;
    ssl_certificate_key     /etc/ssl/thawte/example_com.key;
    ssl_verify_depth 2;
    gzip            on;
    gzip_types      text/plain text/html application/javascript application/json;
    gzip_proxied        any; 

    index index.html;

    location ^~ /index.html {
        gzip_static on;
        root /www/dist;
    }
    location ^~ /images/ {
        expires max;
        root /www/dist;
    }
    location ^~ /scripts/ {
        expires max;
        gzip_static on;
        root /www/dist;
    }

    location ^~ /favicon.ico {
        expires max;
        root /www/dist;
    }

    location ^~ /api {
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $http_host;
        proxy_set_header X-Forwarded-Proto https;
        proxy_redirect off;
        proxy_pass http://django;
    }

    //Send anything else to angular 
    location ~ ^/.+$ {
        rewrite .* /index.html last;
    }

}

这对我们来说非常有效,但我们现在需要将其设置为与 prerender.io 一起使用。我们已经尝试了几种方法,对the official prerender nginx example 进行了修改,但都没有奏效 - 爬虫获取的是与用户相同的代码,而不是缓存页面。

我们怎样才能让它发挥作用?

(注意:这对这里涉及的每个人来说都是新领域,所以如果处理这个问题的最佳方法是退后几步做出不同的选择,请提出建议)

【问题讨论】:

    标签: angularjs nginx pushstate prerender


    【解决方案1】:

    事实证明,上面发布的配置一直在工作。

    当我终于想到尝试将https://example.com/anything 通过爬虫调试器(而不是https://example.com,这是我之前一直在测试的所有内容)时,我意识到了这一点,并且它起作用了 - 为爬虫提供了缓存页面正如预期的那样。

    这仅仅是因为贪婪的量词:

    location ~ ^/.+$ {
    

    与空字符串不匹配。额外的

    location = / {
        try_files $uri @prerender;
     }
    

    ,我的 conf 按预期工作。

    希望我额头上的手印只是通过爬虫调试器输入https://example.com - 这不起作用。

    从好的方面来说,我想下周末我可以把额头上的这个手印变成一件漂亮的万圣节服装......

    仍然不确定我是否采用了最好的方法,欢迎提供其他建议。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-09
      • 2015-05-01
      • 2018-03-13
      • 2020-08-19
      • 2021-11-13
      • 2012-04-27
      • 2023-04-09
      • 1970-01-01
      相关资源
      最近更新 更多