I'm running a client-side rendered React app built using create-react-app which I need to get OpenGraph meta tags working on. I've written some PHP (based on this https://rck.ms/angular-handlebars-open-graph-facebook-share/) which is designed to serve just OpenGraph meta tags for specific pages based on the contents of JSON files. What I need to do is pass requests from crawler user agents to this PHP page from inside NGINX.
server {
server_name example.com www.example.com;
root /var/www/example;
index index.html;
listen 80;
location @crawler {
fastcgi_pass unix:/run/php/php7.0-fpm.sock;
fastcgi_index crawler.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
location / {
if ($http_user_agent ~* "linkedinbot|googlebot|yahoo|bingbot|baiduspider|yandex|yeti|yodaobot|gigabot|ia_archiver|facebookexternalhit|twitterbot|developers\.google\.com") {
proxy_pass @crawler;
}
try_files $uri /index.html;
}
}
This is causing NGINX to fail with the following error:
May 10 00:01:59 ip-172-31-14-46 nginx[10400]: nginx: [emerg] invalid URL prefix in /etc/nginx/sites-enabled/example.com:23
May 10 00:01:59 ip-172-31-14-46 systemd[1]: nginx.service: Control process exited, code=exited status=1
May 10 00:01:59 ip-172-31-14-46 systemd[1]: Reload failed for A high performance web server and a reverse proxy server.
For reference - here's the content of the PHP file:
<?php
// 1. get the content Id (here: an Integer) and sanitize it properly
$uri = $_SERVER[REQUEST_URI];
$hash = hash('md5', $uri);
// 2. get the content from a flat file (or API, or Database, or ...)
$contents = file_get_contents("./meta/". $hash . ".json");
$data = array();
if ($contents) {
$data = json_decode($contents);
}
$data = array_merge(json_decode(file_get_contents("./meta/default.json")), $data);
// 3. return the page
return makePage($data);
function makePage($data) {
// 1. get the page
$pageUrl = "https://example.com" . $uri;
// 2. generate the HTML with open graph tags
$html = '<!doctype html>'.PHP_EOL;
$html .= '<html>'.PHP_EOL;
$html .= '<head>'.PHP_EOL;
$html .= '<title>'.$data->title.'</title>'.PHP_EOL;
$html .= '<meta property="og:title" content="'.$data->title.'"/>'.PHP_EOL;
$html .= '<meta property="og:description" content="'.$data->description.'"/>'.PHP_EOL;
$html .= '<meta property="og:image" content="'.$data->poster.'"/>'.PHP_EOL;
$html .= '<meta http-equiv="refresh" content="0;url='.$pageUrl.'">'.PHP_EOL;
$html .= '</head>'.PHP_EOL;
$html .= '<body></body>'.PHP_EOL;
$html .= '</html>';
// 3. return the page
echo $html;
}