Reed
Reed

Reputation: 1638

nginx conditional pre-render pages for SEO(if + try_files)

For SEO purpose, I have a rendering server that will serve fully rendered webpage to googlebot.

IF UA is googlebot THEN proxy pass to rendering server ELSE serve page normally

Now the problem is, when I mix if and try_files together, it never works.

How can I change the following config to something that works as the above logic?

location ~ ^/web/(.*) {
    if ($http_user_agent ~* "googlebot|bingbot|yandex") {
        proxy_pass http://render.domain.com;
        break;
    }

    try_files $uri /project/$1 /project/dist/$1;
}

Upvotes: 1

Views: 266

Answers (1)

Richard Smith
Richard Smith

Reputation: 49722

You have two regular expressions in that configuration. When nginx encounters a new regular expression, it will reset the numbered captures.

So, whereas you expect $1 to be the capture from the location statement, it is in fact an empty capture from the if statement.

You can use named captures instead. For example:

location ~ ^/web/(?<name>.*) {
    if (...) { ... }    
    try_files $uri /project/$name /project/dist/$name;
}

Upvotes: 1

Related Questions