Search code examples
regexqregularexpression

Regex pattern for CORS origin domain


The CORS origin spec requires the origin to be of the following possibilities:

Origin: <scheme>://<hostname>
Origin: <scheme>://<hostname>:<port>

I would like to have a regex that can match origins with the above criteria; sample domains to match:

http://ex.bar.com
http://www.ex.com
https://ex.bar.com
https://ex.bar.ext:8080

What I have tried is the following:

(^(http|https):\/\/)|(www)|(?!.*(-)\1+)(?:[a-zA-Z]{1}[a-zA-Z0-9-]{0,62}(?<!-)\.)+[a-zA-Z][a-zA-Z0-9-]{0,61}[a-zA-Z0-9]$:{0,61}

But this also matches domains starting with 'www' which I don't need and doesn't match for the port.


Solution

  • I got this working by constructing this regex:

    ^((http|https):\/\/)(?!.*(-)\1+)(?:[a-zA-Z]{1}[a-zA-Z0-9-]{0,62}(?<!-)\.)+[a-zA-Z][a-zA-Z0-9-]{0,61}[a-zA-Z0-9]$|^((http|https):\/\/)(?!.*(-)\1+)(?:[a-zA-Z]{1}[a-zA-Z0-9-]{0,62}(?<!-)\.)+[a-zA-Z][a-zA-Z0-9-]{0,61}[a-zA-Z0-9]+:([1-9][0-9]{0,3}|[1-5][0-9]{4}|6[0-4][0-9]{3}|65[0-4][0-9]{2}|655[0-2][0-9]|6553[0-5])$
    

    The first part matches http://www.ex.com or https://go.ex.com

    ^((http|https):\/\/)(?!.*(-)\1+)(?:[a-zA-Z]{1}[a-zA-Z0-9-]{0,62}(?<!-)\.)+[a-zA-Z][a-zA-Z0-9-]{0,61}[a-zA-Z0-9]$
    

    The second part is a port number check combined with part 1 to match the domain with a given port number, ie.

    ^((http|https):\/\/)(?!.*(-)\1+)(?:[a-zA-Z]{1}[a-zA-Z0-9-]{0,62}(?<!-)\.)+[a-zA-Z][a-zA-Z0-9-]{0,61}[a-zA-Z0-9]
    

    combined with

    +:([1-9][0-9]{0,3}|[1-5][0-9]{4}|6[0-4][0-9]{3}|65[0-4][0-9]{2}|655[0-2][0-9]|6553[0-5])$
    

    I'm sure that might be a better way of doing this or representing the above, please post if someone does know. Thanks!

    Working regex (needs to be trimmed down though):

    ^(\\*$)|^((http|https)://)(?!.*(-)\\1+)(?:[a-zA-Z][a-zA-Z0-9-]{0,62}(?<!-)\\.)+[a-zA-Z][a-zA-Z0-9-]{0,61}[a-zA-Z0-9]$|^((http|https)://)(localhost|(?!.*(-)\\1+)(?:[a-zA-Z][a-zA-Z0-9-]{0,62}(?<!-)\\.)+[a-zA-Z][a-zA-Z0-9-]{0,61}[a-zA-Z0-9])+:([1-9][0-9]{0,3}|[1-5][0-9]{4}|6[0-4][0-9]{3}|65[0-4][0-9]{2}|655[0-2][0-9]|6553[0-5])$