Nginx/Apache redirect based on User Agent

I have built a web application with AngularJs2, when I tried to share one of my page with my Facebook friends, I’d paste the link into the status update box and hope to see my page scrapped and information from OpenGraph protocol used, but unfortunately I saw:

The reason it looks so bad is that crawlers that scrape HTML don’t interpret JavaScript code.

The solution basically is to use some kind of server-side user detection and redirect crawlers to html generated content:

Configuring Nginx to redirect Facebook/Google/Twitter and Pinterest crawlers to html generated page:

Nginx ( add for your current domain configuration ):

 

Apache (.htaccess file):

Those lines will redirect all crawlers to HTML generated content that contains headers with OpenGraph content.

 

For debugging I used cURL:

Observe header content for „User-Agent” and response header „Location”.

Hope this post will help enable rich social sharing for your one page AngularJS app.

Lasă un răspuns

Adresa ta de email nu va fi publicată. Câmpurile obligatorii sunt marcate cu *