<p>Working on putting a Django API into Kubernetes.</p>

<p>Any traffic being sent to <code>/</code> the <code>ingress-nginx</code> controller sends to the React FE. Any traffic being sent to <code>/api</code> is sent to the Django BE.</p>

<p>This is the relevant part of <code>ingress-serivce.yaml</code>:</p>

<pre><code>apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  name: ingress-service
  annotations:
    kubernetes.io/ingress.class: nginx
    nginx.ingress.kubernetes.io/rewrite-target: /$1
spec:
  rules:
    - http:
        paths:
          - path: /?(.*)
            backend:
              serviceName: client-cluster-ip-service
              servicePort: 3000
          - path: /api/?(.*)
            backend:
              serviceName: server-cluster-ip-service
              servicePort: 5000
</code></pre>

<p>This is the <code>url.py</code>:</p>

<p>from django.contrib import admin
from django.urls import include, path</p>

<pre><code>urlpatterns = [
    path('auth/', include('authentication.urls'), name='auth'),
    path('admin/', admin.site.urls, name='admin'),
]
</code></pre>

<p>The <code>client</code> portion works just fine. The <code>minikube</code> IP is <code>192.168.99.105</code>. Navigating to that IP loads the react front-end.</p>

<p>Navigating to <code>192.168.99.105/api/auth/test/</code> brings me to a `"Hello World!" response I quickly put together.</p>

<p>However, when I try to go to <code>192.168.99.105/api/admin</code>. It automatically redirects me to <code>/admin/login/?next=/admin/</code> which doesn't exist given <code>/api</code> is being removed. <strong>Is there anyway to prevent this behavior?</strong></p>

<p>I've also just tried this:</p>

<p><strong>ingress-service.yaml</strong></p>

<pre><code>- http:
    paths:
      - path: /?(.*)
        backend:
          serviceName: client-cluster-ip-service
          servicePort: 3000
      - path: /api/?(.*)
        backend:
          serviceName: server-cluster-ip-service
          servicePort: 5000
      - path: /admin/?(.*)
        backend:
          serviceName: server-cluster-ip-service
          servicePort: 5000
</code></pre>

<p><strong>urls.py</strong></p>

<pre><code>urlpatterns = [
    path('auth/', include('authentication.urls'), name='auth'),
    path('/', admin.site.urls),
]
</code></pre>

<p>Which just produces "Not Found".</p>

<p>I tried to prefix also using this pattern that shows up in <a href="https://docs.djangoproject.com/en/2.2/topics/http/urls/#including-other-urlconfs" rel="nofollow noreferrer">the documentation</a>:</p>

<pre><code>urlpatterns = [
    path('api/', include([
        path('auth/', include('authentication.urls'), name='auth'),
        path('admin/', admin.site.urls),
    ])),
]
</code></pre>

<p>But that just made it <code>/api/api</code>.</p>

<p>Here are the routes that are defined for <code>admin/</code> in the <code>site-packages/django/contrib/admin/sites</code>:</p>

<pre><code># Admin-site-wide views.
urlpatterns = [
    path('', wrap(self.index), name='index'),
    path('login/', self.login, name='login'),
    path('logout/', wrap(self.logout), name='logout'),
    path('password_change/', wrap(self.password_change, cacheable=True), name='password_change'),
    path(
        'password_change/done/',
        wrap(self.password_change_done, cacheable=True),
        name='password_change_done',
    ),
    path('jsi18n/', wrap(self.i18n_javascript, cacheable=True), name='jsi18n'),
    path(
        'r/&lt;int:content_type_id&gt;/&lt;path:object_id&gt;/',
        wrap(contenttype_views.shortcut),
        name='view_on_site',
    ),
]
</code></pre>

<p>I guess the <code>''</code> is what is causing Django to strip the <code>/api</code> off the URL and make it just <code>192.168.99.105/admin</code> instead of <code>192.168.99.105/api/admin</code>.</p>

cjones
<p>Ok, finally figured it out. Definitely was a Django setting. Added the following to the Django <code>settings.py</code>:</p>

<pre><code>FORCE_SCRIPT_NAME = '/api/'
</code></pre>

<p>Then I had to update the <code>STATIC_URL</code> because it was no longer serving the assets for the admin portal:</p>

<pre><code>STATIC_URL = '/api/static/`
</code></pre>

<p>Full <code>settings.py</code> that I'm using, but really the only things that needed changing were adding <code>FORCE_SCRIPT_NAME</code> and updating <code>STATIC_URL</code>:</p>

<pre><code>Django settings for config project.

Generated by 'django-admin startproject' using Django 2.2.6.

For more information on this file, see
https://docs.djangoproject.com/en/2.2/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.2/ref/settings/
"""

import os
from datetime import timedelta

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

# Forces Django to not strip '/api' from the URI
FORCE_SCRIPT_NAME = '/api/'

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = os.environ['SECRET_KEY']

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = os.environ['DEBUG'] == 'True'

ALLOWED_HOSTS = [
        'localhost',
        '127.0.0.1',
        '192.168.64.7'
]


# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',

    # Third-party packages
    'rest_framework',

    # Local packages
    'authentication'
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'whitenoise.middleware.WhiteNoiseMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'config.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'config.wsgi.application'


# Database
# https://docs.djangoproject.com/en/2.2/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': os.environ['PGDATABASE'],
        'USER': os.environ['PGUSER'],
        'PASSWORD': os.environ['PGPASSWORD'],
        'HOST': os.environ['PGHOST'],
        'PORT': 1423
    }
}

# REST Framework settings
# https://www.django-rest-framework.org/
REST_FRAMEWORK = {
    'DEFAULT_RENDERER_CLASSES': [
        'rest_framework.renderers.JSONRenderer',
    ],
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework_simplejwt.authentication.JWTAuthentication',
    ),
    'DEFAULT_PERMISSION_CLASSES': [
        'rest_framework.permissions.AllowAny',
    ],
}

# SIMPLE_JWT Settings
# https://github.com/davesque/django-rest-framework-simplejwt
SIMPLE_JWT = {
    'ACCESS_TOKEN_LIFETIME': timedelta(minutes=5),
    'REFRESH_TOKEN_LIFETIME': timedelta(days=1),
    'ROTATE_REFRESH_TOKENS': False,
    'BLACKLIST_AFTER_ROTATION': True,

    'ALGORITHM': 'HS256',
    'SIGNING_KEY': os.environ['SECRET_KEY'],
    'VERIFYING_KEY': None,
    'AUDIENCE': None,
    'ISSUER': None,

    'AUTH_HEADER_TYPES': ('Bearer',),
    'USER_ID_FIELD': 'id',
    'USER_ID_CLAIM': 'user_id',

    'AUTH_TOKEN_CLASSES': ('rest_framework_simplejwt.tokens.AccessToken',),
    'TOKEN_TYPE_CLAIM': 'token_type',

    'JTI_CLAIM': 'jti',

    'SLIDING_TOKEN_REFRESH_EXP_CLAIM': 'refresh_exp',
    'SLIDING_TOKEN_LIFETIME': timedelta(minutes=5),
    'SLIDING_TOKEN_REFRESH_LIFETIME': timedelta(days=1),
}

# Password validation
# https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]


# Internationalization
# https://docs.djangoproject.com/en/2.2/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'America/Los_Angeles'
USE_I18N = True
USE_L10N = True
USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.2/howto/static-files/
STATIC_URL = '/api/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')

</code></pre>

<p><strong>Dockerfile</strong></p>

<pre><code>FROM python:3.7-slim
ENV PYTHONUNBUFFERED 1
WORKDIR /app
EXPOSE 5000
COPY requirements*.txt ./
RUN pip install -r requirements.txt
COPY . .
RUN python manage.py collectstatic
CMD ["gunicorn", "-b", ":5000", "--log-level", "info", "config.wsgi:application"]
</code></pre>
