Nginx - Multiple / Nested IF Statements

What I want to do:

  • Check if the request comes from Facebook.
  • Check if the URL matches domain.com/2
  • If the above conditions are met - show contents from / api / content / item / $ 1? social = 1
  • If the above conditions are false - show a "normal page"

This is a one page application. Before my change configuration looked like this (and it worked):

location / { root /home/eshlox/projects/XXX/project/project/assets/dist; try_files $uri $uri/ /index.html =404; } 

I tried using if statements:

 location / { set $social 1; if ($http_user_agent ~* "facebookexternalhit") { set $social UA; } if ($uri ~* "^/(\d+)$") { set $social "${social}URL"; } if ($social = UAURL) { rewrite ^/(\d+)$ /api/content/item/$1?social=1; } root /home/eshlox/projects/XXX/project/project/assets/dist; try_files $uri $uri/ /index.html =404; } 

In this configuration, everything works as I expected, only if both conditions are true or false. If one of the conditions is true, and the second is false (or vice versa), then nginx always returns 404 status.

I found "IfIsEvil" on the nginx website, I tried to use the mapping (can I use the mapping in this case?), But still I can not solve this problem.

Any ideas?

Sincerely.

+7
nginx
source share
1 answer

There is a good article about common errors on the nignx wiki.

First, I moved the root directive to the server level. Secondly, location is the best way to check URLs. Therefore, I rethink your requirements as

  • if the location is made up of numbers
  • and request from facebook

we must rewrite the url, and the result:

 root /home/eshlox/projects/XXX/project/project/assets/dist; location / { try_files $uri $uri/ /index.html; } location ~ "^/\d+$" { if ($http_user_agent ~* "facebookexternalhit") { rewrite (.+) /api/content/item$1?social=1; } try_files $uri $uri/ /index.html; } 

In addition, there is almost no reason to have =404 after /index.html in the try_files directive.

+2
source share

All Articles