Nginx: Escaping # in url rewrite

2019-05-10 13:51发布

问题:

I have a MVC JavaScript application that needs to support Facebook sharing, which means it needs to support unique OG meta HTML tags.

I'm doing an Nginx rewrite that will detect the Facebook crawler to server a custom version of the app with the proper OG tag for that section but Apache is ignore everything after the # sign (as server-side should do since that's a browser feature.) I would like to escape the "#" in my rewrite but am not sure how to do it in Nginx:

location / {
  if ($http_user_agent ~* 'facebookexternalhit') {
    rewrite ^(.*)$ /og.php?url=http://$host$uri;
    proxy_pass http://127.0.0.1:8080;
    break;
  }
  root /var/www/html/site.net;
}

Thanks for taking a look!

回答1:

You cannot or don't have to. If you have an URL in your browser like http://www.example.tld/site.html#anchor then your browser's request will only consist of the non-anchor part: http://www.example.tld/site.html. After receiving the content the browser will look for a named anchor called anchor and scroll the page so that its content is visible.

Meaning nginx will never see the character #.

If, on the other hand, a website contains a link with # being part of the path part of the URL (and this is rather rare) then it has to be escaped with the usual URL escaping of %xx with xx being the hexadecimal number of that chacter -- %23 in the case of #.