Set up different CORS rules based on the endpoint in Django

Stack Overflow Asked by Augusto Samamé Barrientos on December 12, 2020

I’m trying to figure out a way to have different CORS rules based on the backend endpoint frontend would hit.

So I can have

/api endpoint with a CORS domain whitelist and

/public-api without a CORS domain whitelist.

This is needed because I have both internal endpoints I use for my own frontend, and a public JS widget that can be installed in any 3rd party domain.

I’ve looked at django-cors-headers library, but it’s regex configuration


works to let requests FROM a list of domains through.

In my case, I need to a way to have a regex (or another method) to let requests TO my endpoints through or not.

2 Answers

django-cors-headers allows you to specify a custom handler function that will check if the request should be allowed. In your case you can use something like this:

# myapp/
from corsheaders.signals import check_request_enabled

def cors_allow_particular_urls(sender, request, **kwargs):
    return request.path.startswith('/public-api/')

check_request_enabled.connect(cors_allow_mysites) needs to be loaded in app config:

# myapp/

default_app_config = 'myapp.apps.MyAppConfig'
# myapp/

from django.apps import AppConfig

class MyAppConfig(AppConfig):
    name = 'myapp'

    def ready(self):
        # Makes sure all signal handlers are connected
        from myapp import handlers  # noqa

More info here:

Correct answer by Olzhas Arystanov on December 12, 2020

If you can club your private URLs under a separate prefix (ex: /private/<something>) you can use CORS_URLS_REGEX=r'^/private/.*$'

You can read more about it here:

Answered by anilkumarggk on December 12, 2020

Add your own answers!

Related Questions

Substring instead of Left

2  Asked on January 5, 2021


R: Multi-type Point Pattern scan.test

1  Asked on January 5, 2021 by clemson


Pandas: filter rows with loc on anonymous dataframe

2  Asked on January 5, 2021 by user3579222


Why are the spacings in the decipher incorrect?

2  Asked on January 4, 2021 by iliketocode123465


How to play more than one stream at once using soundio?

1  Asked on January 3, 2021 by 010110110101


Units and Measurements in Swift

1  Asked on January 3, 2021 by tick_hoges


Count files in directory (python)

0  Asked on January 3, 2021 by user14606934


How to set the “Resource root URL” in Jenkins

1  Asked on January 3, 2021 by hephaestus


Write Pandas DataFrame to chronologic excel sheet

0  Asked on January 3, 2021 by anna-bleha


Ask a Question

Get help from others!

© 2022 All rights reserved. Sites we Love: PCI Database, MenuIva, UKBizDB, Menu Kuliner, Sharing RPP