我希望在nginx中以这样的方式处理请求,所以当爬行器来获取一个请求的页面时,我需要通过请求的URL发送一个静态版本的单页应用程序,否则动态生成index.html
。静态和动态页面位于不同的文件夹中(必需的),所以我在这种情况下使用$src
变量。
我的配置:
server {
listen 443 ssl http2;
server_name www.example.com;
set $src "/www";
set $crawler 0;
if ($http_user_agent ~* "examplebot|anotherbot|crawlerbot") {
set $crawler 1;
set $src "/www-static";
}
root "/var${src}";
location ~* ^/(en|us|uk)/products/ {
if ($crawler = 1) {
rewrite ^/(\w\w)/products/(\w+)/(\w+) /pages/$1/$2/$3.html break;
}
}
location / {
try_files $uri /index.html;
}
}
有了上面的配置,当我去我的网站我得到404
错误,即使通过一个正常的用户代理(不是爬虫的)。
爬网程序请求URL:https://www.example.com/en/products/dairy/cheese
静态页面位置:/var/www-static/pages/en/dairy/cheese.html
我的期望是,当爬虫请求例如https://www.example.com/en/products/dairy/cheese
时,它应该得到静态页面,而当普通用户请求任何页面时,他应该得到位于根文件夹中的 index.html。
我知道nginx中的if
语句并不是世界上最好的东西,但是有没有什么解决方案可以实现我想要的,不管有没有if
或者rewrite
语句,谢谢?
我想指出的是,“重定向”到所需的文件夹与$src
变量没有第一个location
块的工作没有问题。所以,我认为问题是没有联系到$src
变量和它的逻辑。
1条答案
按热度按时间qacovj5a1#
向
index.html
发送请求的逻辑是try_files
语句。要复制location ~* ^/(en|us|uk)/products/
块处理的URL的行为,您还需要在该块中添加一条try_files
语句。例如: