CORS URL Matching Using Wildcards

I need to map CORS URLs that satisfy the following requirements:

Schemes: "http" and "https"

The local host must be allowed.

The host may have a symbol -

May have a wildcard *for the whole subdomain or destination template *.

Part of the TLD is optional

Segments have a size limit of {1.63}

Allowed:

https://localhost.localdomain
http://127.0.0.1
http://*.example.com
http://my*.example.com
https://env-us.example.com
https://*.example.com
https://*.example.net
http://localhost (hardcoded to allow)

Is not allowed:

https://www.test.012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789
https://012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789.com
http://m*y.example.com
http://*my.example.com
http://.example.com
http://example.com*
http://-.com
http://z-.com
https://my.best-example*.best-example*.com
http://127*.0.0.1
https://my.*.com
+4
source share
4 answers

you can use

^(?:https?://)?(?:[-\w]*(?:\*(?=\.))?(?:\.[-\w]{1,63})+)$

Watch the demo at regex101.com . Please note that \walready includes \d.


Broken, it says:
^                      # start of the string
(?:https?://)?         # http:// or https://, optional
(?:[-\w]*(?:\*(?=\.))? # - or word characters, followed by a star and a dot
(?:\.[-\w]{1,63})+)    # host part
$                      # the end of the string
+2
source

, ( ) / :

^(https?://)?(([\w\d]+(-[\w\d]+)*)*\*?\.)*(\w+)((\.\w{2,63})?)$
+1

I made the following changes to your regular expression:

  • [\\w\\d]changed to \\w. The word char ( \w) also includes the number ( \d).
  • +after (-[\\w\\d]+)changed to *. -...the name of the part (sub) is optional.
  • Then I added \\*?for the (optional) final star.

So my regex, without a double backslash, is as follows:

^(https?://)?((\*|\w+(-\w+)*)\*?\.)*(\w+)((\.\w{2,63})?)$
+1
source

Based on the accepted answers and updated requirements, the following regular expression works:

^(https?:\/\/)?(([12]?\d?\d(\.[1-2]?\d?\d){3})|(([a-zA-Z][-\w]{0,61}\w\*?)|(\*)){1}(\.[-\w]{1,63}?)*(\.[\w]{1,63}))$
+1
source

Source: https://habr.com/ru/post/1692871/


All Articles