8

Question says it almost all.

E.g. changing default url (http://127.0.0.1:8000) to a custom (https://api.example.com/v1)

I'm using HyperlinkedModels and everything seems to work properly in development. Moving the app to another server with custom url is giving me problems.

How do I change the default url:

default url 127.0.0.1:8000

To a custom one, let's say:

https://api.example.org/v1/

mimoralea
  • 9,590
  • 7
  • 58
  • 59

1 Answers1

22

You are mixing two questions in one:

  1. How to run django-rest-framework project on a different domain
  2. How to change URL path of API

To answer the first one I'd say, "Just do it". Django's reverse uses request's domain to build absolute URL.

UPDATE: don't forget to pass Host header from nginx/apache. Below is a sample nginx config:

server {

    location / {
        proxy_set_header        Host $host;
        proxy_set_header        X-Real-IP $remote_addr;
        proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header        X-Forwarded-Proto $scheme;
        proxy_pass              http://127.0.0.1:8000;
    }

}

The second (path, mount point) is set in the urls.py:

from django.conf.urls import url, include
from django.contrib import admin

from rest_framework import routers

from quickstart import views

router = routers.DefaultRouter()
router.register(r'users', views.UserViewSet)
router.register(r'groups', views.GroupViewSet)


urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),
    url(r'^v1/', include(router.urls)), # <-------------- HERE
]

enter image description here

twil
  • 6,032
  • 1
  • 30
  • 28
  • Thanks for posting. Would this work even with a gunicorn/nginx setup? This is kind-of the way I have it, yet it still shows '127.0.0.1'. https://api.nutrislots.com/api/ – mimoralea Dec 15 '15 at 21:35
  • Oh, I see. Most probably you've lost `proxy_set_header Host $host;` parameter in nginx configuration. I've updated answer with a sample nginx config. – twil Dec 15 '15 at 22:12
  • It wasn't even drf... I wish I could `+1 * 5`. Thanks twil. – mimoralea Dec 17 '15 at 14:26
  • What if I'm using apache2 instead nginx? How to fix this? –  Jun 15 '20 at 20:30
  • 1
    @DenisSoto what config do you have/tried? I'm not that good with the apache but this directive looks promising [ProxyPreserveHost](https://httpd.apache.org/docs/2.4/mod/mod_proxy.html#proxypreservehost) – twil Jun 15 '20 at 20:40