Skip to content

Instantly share code, notes, and snippets.

@DarkFighterLuke
Last active March 17, 2024 11:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DarkFighterLuke/4561b6bfbf83720493dc59171c58ac36 to your computer and use it in GitHub Desktop.
Save DarkFighterLuke/4561b6bfbf83720493dc59171c58ac36 to your computer and use it in GitHub Desktop.
Set base URL for TubeArchivist with Nginx
js_path "/etc/nginx/conf.d/";
js_import main from ta_filter.js;
js_set $body_hash main.get_hash;
server {
location /multimedia/tubearchivist/ {
rewrite ^/multimedia/tubearchivist(.*)$ $1 break;
proxy_pass http://{{subnets.multimedia}}.0.14:8000;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header Host $http_host;
proxy_set_header Accept-Encoding identity;
proxy_redirect ~^(.*)$ /multimedia/tubearchivist$1;
js_body_filter main.apply_base_url;
add_trailer Body-Hash $body_hash;
}
}
var hash = "";
var res = "";
var buf = 0;
// Modify the response body using regular expressions
function apply_base_url(r, data, flags) {
let requestUrl = r.uri;
let fileExtension = getFileExtension(requestUrl)
if (fileExtension === "" || fileExtension === "css" || fileExtension === "js") {
// Replace URLs in API responses
if (requestUrl.includes("/api/")) {
data = data.replace(/("[^"\n\r\f\v]*"(?=\s*:):")(\/.*?")/g, '$1/multimedia/tubearchivist$2');
} else {
// Fix some hardcoded /api in JS scripts
if (fileExtension === "js") {
data = data.replace(/`(\/api.*)/g, '`/multimedia/tubearchivist$1');
}
data = data.replace(/(src|href|action)=["'](\/.*?)["']/g, '$1="/multimedia/tubearchivist$2"');
data = data.replace(/'(\/.*)'/g, '\'/multimedia/tubearchivist$1\'');
}
}
if (data.length) buf++;
res += data; // Collect the entire response,
if (flags.last) { // until we get the last byte.
try {
hash = require('crypto').createHash('sha1').update(res).digest('base64');
r.sendBuffer(res, flags);
ngx.log(ngx.INFO, `FILTERED ${res.length} bytes in ${buf} buffers`);
} catch (e) {
ngx.log(ngx.ERR, `ERROR ${e}`);
r.sendBuffer("", flags);
}
}
}
// Extract the file extension from the URL
function getFileExtension(url) {
let match = url.match(/\.([a-z0-9]+)(?:[\?#]|$)/i);
return match ? match[1].toLowerCase() : '';
}
function get_hash() {
return hash;
}
export default {
apply_base_url,
get_hash
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment