4

I currently have .htaccess file that lists dozens of domains to enable CORS to from my server.

I shortened my example below , but all the domain names are similar and the only part of the domain name that is changed is the 1 or 2 digit number after the www.

<IfModule mod_headers.c>
    SetEnvIf Origin "http(s)?://(www48.example.com||www47.example.com)$" AccessControlAllowOrigin=$0
        Header add Access-Control-Allow-Origin %{AccessControlAllowOrigin}e env=AccessControlAllowOrigin
        Header merge Vary Origin
</IfModule>

so in this example i have CORS enabled for

https://www48.example.com
https://www47.example.com

I was wanting a simpler way to enable a list of of 99 domains with similar names. So all domain names are identical aside of digits 1 to 99 after the "www" , how can I achieve this without listing all 99 domain names individually?

https://www1.example.com
https://www2.example.com
....
https://www10.example.com
....
https://www40.example.com
....
https://www70.example.com
....
https://www99.example.com
MrWhite
  • 43,179
  • 8
  • 60
  • 84
MShack
  • 642
  • 1
  • 14
  • 33
  • 1
    Instead of using alternation for the full host names, match digits in the specific position? Something like `www[1-9][0-9]?\.domainname\.com` – CBroe Jun 05 '23 at 06:28
  • can you expand your suggestion to include what i have ? – MShack Jun 05 '23 at 22:09

1 Answers1

5

This seems to work , anyone review and see if ok

<IfModule mod_headers.c>
    SetEnvIf Origin "http(s)?://(www[1-9][0-9]?\.example\.com)$" AccessControlAllowOrigin=$0
        Header add Access-Control-Allow-Origin %{AccessControlAllowOrigin}e env=AccessControlAllowOrigin
        Header merge Vary Origin
</IfModule>
MrWhite
  • 43,179
  • 8
  • 60
  • 84
MShack
  • 642
  • 1
  • 14
  • 33
  • That's fine, except for a few minor things regarding the regex: **#1** No need for the _capturing_ subgroups. **#2** The `s` on `https` should probably not be _optional_? **#3** If you re going to anchor the regex then why not anchor the start? **#4** `[0-9]` is the same as shorthand `\d`. So, it would become: `"^https://www[1-9]\d?\.example\.com$"` – MrWhite Jun 06 '23 at 09:25
  • And there's probably no need for the `` wrapper, unless these directives are considered _optional_? – MrWhite Jun 06 '23 at 09:27
  • thanks MrWhite , that worked perfectly – MShack Jun 06 '23 at 11:11
  • Good solution but could've explained it a bit more – MaikeruDev Jun 12 '23 at 11:44
  • As @MrWhite mentioned, the capturing does appear to be necessary. The subsequent _AccessControlAllowOrigin_ assignment uses $0, which would be the entire match. So, ^https?://www[1-9]\d?\.example\.com$, would suffice. – Reilas Jun 12 '23 at 23:14