Search and replace in strings

Use regular expression substitution functions (regsub) to map paths, strip extraneous slashes, and more.

VCL

Use this solution in your VCL service (click RUN below to test this solution or clone it to make changes):

Compute@Edge

Use this solution in your Compute@Edge service:

  1. Rust
// Log initial setup
log_fastly::init_simple("my_log", log::LevelFilter::Info);
let mut resp_body = String::new();
{
let input = "/foo///bar//baz";
let regex = "/+";
let replace = "/";
let output = Regex::new(regex)?.replace_all(input, replace);
let log_line = format!(
"Replace multiple //// in URL paths with a single one: {} {}",
input, output
);
log::info!("{}", log_line);
writeln!(&mut resp_body, "{}", log_line)?;
}
{
let input = "www.example.com";
let output = input.strip_prefix("www.").unwrap_or(input);
let log_line = format!("Remove leading www. from host header: {} {}", input, output);
log::info!("{}", log_line);
writeln!(&mut resp_body, "{}", log_line)?;
}
{
let input = "/foo/bar/";
let output = input.strip_suffix('/').unwrap_or(input);
let log_line = format!("Remove trailing slash: {} {}", input, output);
log::info!("{}", log_line);
writeln!(&mut resp_body, "{}", log_line)?;
}
{
let input = "/products/furbles/12345/photos";
let regex = r"^/products/(\w+)/(\d+)(/(\w+))?$";
let replace = "/legacy.cgi?cat=$1&id=$2&page=$4";
let output = Regex::new(regex).unwrap().replace(input, replace);
let log_line = format!("Map path parameters: {} {}", input, output);
log::info!("{}", log_line);
writeln!(&mut resp_body, "{}", log_line)?;
}
Ok(Response::from_body(resp_body))