Nginx – Use sub_filter on different urls serving same html page

nginxredirect

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.

Best Answer

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;
}