Forum Discussion

ringoseagull_77's avatar
ringoseagull_77
Icon for Nimbostratus rankNimbostratus
Mar 25, 2011

irule to remove www. prefix from URIs

Hi,

 

 

I'm sure this has been covered but a search brings up a lot of threads using the same words

 

 

I need an irule which just strips out the www. from an http request, eg redirect www.mysite.com to mysite.com

 

 

Can someone point me towards one please?

 

6 Replies

  • Here you go:

    when HTTP_REQUEST {
    
        Check if the host starts with www.
       if {[string tolower [HTTP::host]] starts_with "www."}{
    
           Redirect with the www. prefix removed to the same URI
          HTTP::redirect "http://[string range [HTTP::host] 4 end][HTTP::uri]"
       }
    }
    

    If this is for HTTPS, your cert is only valid for example.com and the client requests www.example.com, this iRule won't prevent a cert mismatch warning. You'd also need to change the redirect from http:// to https://.

    Aaron
  • My boss has just requested one that does the opposite, to redirect mysite.com to www.mysite.com.

     

     

    Do you have one for that too?

     

     

  • Sure:

    
    when HTTP_REQUEST {
    
        Check if the host does not start with www.
       if {not ([string tolower [HTTP::host]] starts_with "www.")}{
    
           Redirect with the www. prefix to the same URI
          HTTP::redirect "http://www.[HTTP::host][HTTP::uri]"
       }
    }
    

    Aaron
  • Thanks, I found this by searching, it will do the same job by the looks, unless the string to lower segment makes a difference?

     

     

    when HTTP_REQUEST {

     

    if { ! ([HTTP::host] starts_with "www.") } {

     

    HTTP::redirect http://www.[HTTP::host][HTTP::uri]

     

    }

     

    }

     

     

    Thanks again for your help
  • I've used your version anyway, and amended the redirect line to o https for the 443. Thanks hoolio.