Forum Discussion

UniFirst1_22521's avatar
UniFirst1_22521
Icon for Nimbostratus rankNimbostratus
Feb 21, 2019

301 redirect replacing www if present

Trying to create an iRule that will redirect HTTP to HTTPS and remove example incoming would be http://www.unifirst.ca and it would be redirected to https://unifirst.ca with a 301 response not a 302.

I have the following iRule written

when HTTP_REQUEST { if { [string tolower [HTTP::host]] starts_with "; } then { HTTP::respond 301 "Location" "https://[findstr [string tolower [HTTP::host]] "; 4][HTTP::uri]" } else { HTTP::respond 301 "Location" "https://[HTTP::host]][HTTP::uri]" } }

but it gives me the following error in the browser when trying http://unifirst.ca

This page isn’t working unifirst.ca sent an invalid response.
ERR_INVALID_REDIRECT

I have tried with different browsers and get same results.

Any ideas?

2 Replies

  • Try this:

    when HTTP_REQUEST { 
        if { [string tolower [HTTP::host]] starts_with "www." } { 
            set host [ string map {'www.' ''} [HTTP::host] ]
            HTTP::redirect "https://$host[HTTP::uri]"
        } else { 
            HTTP::redirect "https://[HTTP::host][HTTP::uri]" 
        }
    }
    
  • wlopez's avatar
    wlopez
    Icon for Cirrocumulus rankCirrocumulus

    What are the different hostnames/URLs you're planning to redirect from http to https on the http virtual server?

    If you're only managing a single domain with two URL variants (Ex. , unifirst.ca) the simplest way would be to redirect all http requests to the desired hostname:

    when HTTP_REQUEST {
        HTTP::respond 301 Location "https://unifirst.ca[HTTP::uri]"
    }