nginx try_files with add_header

2019-08-03 22:17发布

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?

0条回答
登录 后发表回答