.htaccessvue.jsweb-crawlerfacebook-share

redirect htaccess for facebook crawler


I've created a SPA app with vuejs. Everything was perfect until I want to share dynamic content on Facebook.

After research I found that I need another file (In my case php file) when I fill the meta-tags for facebook crawler. In htaccess I'm trying to detect to Facebook agents and to redirect to specific file to fill meta-tags.

This is my .htaccess:

<IfModule mod_rewrite.c>
<IfModule mod_negotiation.c>
    Options -MultiViews
</IfModule>

RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /index.html [NC,QSA]

# Handle Authorization Header
RewriteCond %{HTTP:Authorization} .
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

# Crawler
RewriteCond %{HTTP_USER_AGENT} (facebookexternalhit/[0-9]|Facebot|Twitterbot|Pinterest|Google.*snippet)
RewriteRule cars/carDetail(.*)$ http://website.api.com/v1.0/meta-tags$1 [R=301,L]

But is not working. When you try to debug from https://developers.facebook.com/tools/debug/sharing/ url:

http://website.com/cars/carDetail?id=48

Is not redirecting to:

http://website.api.com/v1.0/meta-tags$1

Thanks


Solution

  • I solved my problem.

    The redirect condition should be on the top of htaccess. Also I've add "RewriteBase /" option on the top:

    <IfModule mod_rewrite.c>
    
     RewriteEngine On
     RewriteBase /
    
    # allow social media crawlers to work by redirecting them to a server-rendered static version on the page
    RewriteCond %{HTTP_USER_AGENT} (facebookexternalhit/[0-9]|Twitterbot|Pinterest|Google.*snippet)
    RewriteRule cars/carDetail(.*)$ http://website.api.com/v1.0/meta-tags$1 [R=301,L]
    
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)$ /index.html [NC,QSA]
    
    # Handle Authorization Header
    RewriteCond %{HTTP:Authorization} .
    RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] 
    </IfModule>