Forum Discussion

UniFirst1_22521's avatar
UniFirst1_22521
Icon for Nimbostratus rankNimbostratus
Jan 14, 2019

Using an iRule to redirect with a 301 response code

Trying to redirect using a iRule first removing any www from the header and sending back a 301 response. I have the following iRule for removing the www from the header. However, not sure how to do the 301 response. Would like to do both in same irule. The default 302 is not acceptable.

 

when HTTP_REQUEST { if { [string tolower [HTTP::host]] starts_with "; } { HTTP::redirect "https://[findstr [string tolower [HTTP::host]] "; 4][HTTP::uri]" } }

 

Any ideas? Thanks

 

2 Replies

  • I believe this iRule should work for you.

    when HTTP_REQUEST {
    if { [string tolower [HTTP::host]] starts_with "www." } 
        { 
            HTTP::respond 301 "Location" "https://[findstr [string tolower [HTTP::host]] "www." 4][HTTP::uri]" 
        } 
    }
    
  • Given that you want to remove a fixed-length string from the start of the host name, either of the following may be simpler and more efficient than using the 'findstr' command:

    when HTTP_REQUEST {
    if { [string tolower [HTTP::host]] starts_with "www." } 
        { 
         use one or the other but not both
            HTTP::respond 301 "Location" "https://[substr [HTTP::host] 4][HTTP::uri]" 
            HTTP::respond 301 "Location" "https://[string range [HTTP::host] 4 end][HTTP::uri]"             
        } 
    }
    

    The 'substr' command skips the first four characters of the host name (i.e. ";), as does the 'string range' command.