user1909643
user1909643

Reputation: 31

varnish split url and change url

Is there a way to split url on varnish or change url structure with it.

I know regsub or regsuball support that but they are not enough in my case.

I would like to change a url and redirect it to another domain.

For example:

http://aaa.test.com/sport/99244-article-hyun-jun-suku-kapa.html?

to redirect below address

http://m.test.com/article-hyun-jun-suku-kapa-sport-99244/

I added some lines in vcl file to do that

set req.http.xrul=regsuball(req.url,".html","");  "clear .html"

set req.http.xrul=regsub(req.http.xrul,"(\d+)","\1"); find numbers --article ID =99244

I can rid of the article ID with

set req.http.xrul=regsub(req.http.xrul,"(\d+)",""); 

but cannot get just only article ID

set req.http.xrul=regsub(req.http.xrul,"(\d+)","\1"); or any other method 

Does varnish support split the url with "-" pattern thus I could redesign the url? Or can we get only articleID with regsub?

Upvotes: 0

Views: 2011

Answers (1)

Rastislav Kassak
Rastislav Kassak

Reputation: 148

Is this what you want to achieve?

set req.http.X-Redirect-URL = regsuball(req.url,"^/([^/]*)/([0-9]+)-([^/]+)\.html$","http://m.test.com/\3-\1-\2");

This is working code tailored to example you provided, just one level of section placement.

If you want to support more levels of sections, you only have to adjust regexp a bit and replace / to - in second step:

set req.http.X-Redirect-URL = "http://m.test.com/" + regsuball(regsuball(req.url, "^/(.*)/([0-9]+)-([^/]+)\.html$", "\3-\1-\2"), "/", "-");

Maybe you need one more refinement. What if URL doesn't match you pattern? X-Redirect-URL will be the very same value as req.url is. You definitely don't want redirect loop, so I suggest to add mark character to the begin of X-Redirect-URL and then test for it.

Let's say:

set req.http.X-Redirect-URL = regsuball(regsuball(req.url, "^/(.*)/([0-9]+)-([^/]+)\.html$", "#\3-\1-\2"), "/", "-");
if(req.http.X-Redirect-URL ~ "^#") {
    set req.http.X-Redirect-URL = regsuball(req.http.X-Redirect-URL, "#", "http://m.test.com/");
    return(synth(391));
} else {
    unset req.http.X-Redirect-URL;
}

and for all cases, you need in vcl_synth:

if (resp.status == 391) {
        set resp.status = 301;
        set resp.http.Location = req.http.X-Redirect-URL;
        return (deliver);
}

Hope this helps.

Upvotes: 0

Related Questions