Preserving Port Number When Redirecting

I’m using a redirect rule to remove the www. subdomain from URLs:

But when I add a port:
www.example.com:2096

It redirects to:
example.com

Instead to:
example.com:2096

How to preserve the port in this redirect rule?

Havent tried it personally, but you should be able to add the cf.edge.server_port field in your concat.
More on what that field is here:

2 Likes

I’ve tried this but I’m getting an error:

concat("https://",substring(http.host,4),cf.edge.server_port,http.request.uri.path)

Any ideas on how to form it better?

I’ve not tried it, but probably needs this…

concat("https://",substring(http.host,4),":",to_string(cf.edge.server_port),http.request.uri.path)

2 Likes

Correct! Beat me to it.
concat("https://", substring(http.host, 4),":",to_string(cf.edge.server_port),http.request.uri.path) works great for me.

(Why?) - concat() joins fields of a string type. the port is returned as an integer so cant be used in the join. We can convert it to a string using the function to_string() which then lets us treat it as such.

2 Likes

It works for URIs with a port but for URIs without the port, it returns this:

https://www.example.com/ => https://example.com:443/

My suggestion is to add more preservation options like “Preserve query string”. You can add “Preserve port” or maybe “Preserve URI path”. I know you can add these to the expression but it’s easier this way.

If thats a problem you can always adjust the expression, e.g. AND cf.edge.server_port ne 443 (again, havent tested this, you might need to tweak the syntax).

1 Like

This topic was automatically closed 3 days after the last reply. New replies are no longer allowed.