3

I am trying to hack around the fact that SPA (i.e. javascript rendered pages) cannot serve twitter metadata and the metadata has to be part of the server html page. There are many proper solutions to this problem like server-side rendering but I am looking for a quicker way since I want this for a page served by just 3 different urls.

What I want to achieve is:

  • http://example.com => serves index.html normally (index.html has the meta header tags hardcoded)

  • http://example.com/accept serves index.html but with meta tags replaced through the usage of sub_filter having the word accept in there

  • http://example.com/reject serves index.html but with meta tags replaced through the usage of sub_filter having the word reject in there

I tried using different locations like:

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

location /accept {
  sub_filter 'normal'  'accept';
  sub_filter_once off;
  try_files $uri /index.html;
}

But I get served the index.html with the normal meta tags. If i move the sub_filter in the / location then string replacement works though.

Also experimented with rewrite, if inside location etc but couldn't get it to work.

2 Answers 2

3

The final element of the try_files statement looks for another location to process the request for /index.html, which is why it is not processed in the same location block.

You can use an alias directive or a rewrite...break to keep processing within the same location block.

location /accept {
    default_type text/html;
    alias /path/to/index.html;

    sub_filter 'normal'  'accept';
    sub_filter_once off;
}

Or:

location /accept {
    rewrite ^ /index.html break;

    sub_filter 'normal'  'accept';
    sub_filter_once off;
}
1
  • rewrite break worked, although I am sure I tried it before, but couldn't make it work! alias did not work for me but that's ok. Thanks a million.
    – masimplo
    Oct 8, 2017 at 16:49
1

Richard Smith was right, it's the last element of try_files (fallback) that causes the problem because the fallback is processed in another context. So the easiest answer is to make index.html not the last element anymore.

location /accept {
  sub_filter 'normal'  'accept';
  sub_filter_once off;
  try_files $uri /index.html /index.html; # notice this with 2 index.html
}

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .