7

Can someone explain this?

I have an nginx server block with this snippet in it:

location / {
  try_files $uri $uri/ /index.html;
}

Basically, I'm using this to serve an Angular SPA. It works well and great.

Now I wanted to append Access-Control-Allow-Origin header to the response. So I changed the block like so:

location / {
  if ($request_method = 'OPTIONS') {
          add_header 'Access-Control-Allow-Origin' '*';
          add_header 'Access-Control-Max-Age' 1728000;
          return 204;
  }
  if ($request_method = 'GET') {
          add_header 'Access-Control-Allow-Origin' '*';
  }
  try_files $uri $uri/ /index.html;
}

Now whenever I access http://<application>.com I get the page and I'm able to navigate to subroutes like http://<application>.com/some-page. But if I directly try to access http://<application>.com/some-page, I'm getting an nginx 404. It wasn't the case before. If I comment out the if statement for GET, things go back to normal.

Why? What difference does the if statement make here?

Rajshri Mohan K S
  • 1,557
  • 17
  • 30
  • 3
    You should [read this](https://www.nginx.com/resources/wiki/start/topics/depth/ifisevil/) – Richard Smith May 10 '18 at 11:57
  • 3
    @RichardSmith Wow. Thanks. That was useful indeed. I kind of solved my situation by moving the `try_files` inside the `if` with GET block. Any idea if there's a more elegant way to do it? – Rajshri Mohan K S May 10 '18 at 18:07

0 Answers0