Skip to content

Instantly share code, notes, and snippets.

@g105b
Last active April 1, 2020 14:40
Show Gist options
  • Save g105b/0ba16f5639cc70a188d09ba38ba7e482 to your computer and use it in GitHub Desktop.
Save g105b/0ba16f5639cc70a188d09ba38ba7e482 to your computer and use it in GitHub Desktop.
Redirects things from a CSV of old paths
server {
server_name example.com www.example.com;
listen 80;
location / {
fastcgi_pass unix:/var/run/php/php7.4-fpm.sock;
include fastcgi_params;
fastcgi_param SERVER_NAME $host;
fastcgi_param SCRIPT_FILENAME /var/www/path/to/router.php;
}
}
<?php
// Adjust constants as desired.
// CSV must have old URL in first column, new URL in second column.
const CSV_PATH = __DIR__ . "/redirects.csv";
const STATUS_CODE = 303;
const REDIRECT_IF_NO_MATCH = "http://example.com";
$requestUri = $_SERVER["REQUEST_URI"] ?? $argv[1] ?? "/";
$requestUri = parse_url($requestUri, PHP_URL_PATH);
$csv = fopen(CSV_PATH, "r");
while(!feof($csv)) {
list($from, $to) = fgetcsv($csv);
$fromPath = parse_url($from, PHP_URL_PATH);
if($requestUri === $fromPath) {
header("Location: $to", true, STATUS_CODE);
exit;
}
}
header("Location: " . REDIRECT_IF_NO_MATCH, true, STATUS_CODE);
exit;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment