奇怪的重定向与proxy_pass在if语句
我有一个SPA(单页应用程序)的网站,让我们https://example.com下说和https://api.example.com奇怪的重定向与proxy_pass在if语句
我想成为像googlebot
具体useragents服务器呈现的内容下它的API, facebookexternalhit
等
所以,如果用户进入https://example.com/brandon/things将获得服务的SPA,但如果机器人去相同的URL将得到服务的服务器呈现的页面与所有适当元和开放的图形标记。
我的服务器渲染的适当匹配的网页正在https://api.example.com/ssr/
因此,举例来说,如果僵尸打https://example.com/brandon/things应该从https://api.example.com/ssr/brandon/things
获取内容我差点它与nginx的proxy_pass工作,如果语句的Django应用程序(它返回服务器呈现的输出),但不幸的是有一个边缘案例使其行为异常。
我的实现:
server {
listen 80;
server_name example.com; # url of SPA
index index.html;
root /srv/example_spa/public/dist; # directory of SPA index.html
# $ssr variable that tells if we should use server side rendered page
set $ssr 0;
if ($http_user_agent ~* "googlebot|yahoo|bingbot|baiduspider|yandex|yeti|yodaobot|gigabot|ia_archiver|facebookexternalhit|facebot|twitterbot|developers\.google\.com|rogerbot|linkedinbot|embedly|quora link preview|showyoubot|outbrain|pinterest|slackbot|vkShare|W3C_Validator|redditbot") {
set $ssr 1;
}
# location block that serves proxy_pass when the $ssr matches
# or if the $ssr doesn't match it serves SPA application index.html
location/{
if ($ssr = 1) {
proxy_pass http://127.0.0.1:9505/ssr$uri$is_args$args;
}
try_files $uri /index.html;
}
}
但是有问题:
一切工作的花花公子和甜蜜,除了一种情况。
用户点击https://example.com/brandon/things/
他得到SPA index.html - 完美。
用户点击https://example.com/brandon/things
他得到SPA index.html - 完美。
机器人点击https://example.com/brandon/things/
他得到服务器呈现页面完美。
博特命中https://example.com/brandon/things
(不含附加斜线),他被重定向(301)https://example.com/ssr/brandon/things
- BAD BAD BAD
我试图使它的几个小时,现在的工作没有运气。 你会建议什么?我知道,如果在nginx的是邪恶的,但我不知道如何度过,即使没有它的工作...
任何帮助表示赞赏
您需要更改的重新导向proxy_pass
location/{
proxy_redirect http://127.0.0.1/ssr/ http://$host/ssr/;
proxy_redirect /ssr/ /;
if ($ssr = 1) {
proxy_pass http://127.0.0.1:9505/ssr$uri$is_args$args;
}
try_files $uri /index.html;
}
事实证明,这是我的Django应用程序重定向的问题。我以为我已禁用“APPEND_SLASH”选项,但在没有斜线时启用并重定向。并且它重定向而不更改主机到https://api.example.com,但只有URI部分。因此我的困惑。
我实际上找到了两种方法来解决这个问题。
首先,只需使用重写追加斜线时,没有之一。
location/{
if ($ssr = 1) {
rewrite ^([^.]*[^/])$ $1/ permanent;
proxy_pass http://127.0.0.1:9505/ssr$uri$is_args$args;
}
try_files $uri /index.html;
}
二,修改proxy_pass总是后$ URI部分和服务器端添加/斜线渲染应用程序URL配置在年底//”接受两条斜线。这是一个有点哈克,但没有副作用,并应如其工作。
Nginx的配置:
location/{
if ($ssr = 1) {
proxy_pass http://127.0.0.1:9505/ssr$uri/$is_args$args;
}
try_files $uri /index.html;
}
Django的URL正则表达式:
r'^ssr/(?P<username>[\w-]+)/(?P<slug>[\w-]+)(/|//)$'
嗨,感谢您的回答!我实际上第二天找到了一个解决方案,我在这里添加了它。这个问题并没有出现在nginx中,但我的应用程序重定向了。 –