Configure NGINX to Run Django App in a Sub Path

Sometimes we need to run our Django project in sub path of parent URL ( www.yourmainurl.com/yourproject ) and when I have this situation I researched a lot and finally found my solution. Here I have tried to solve your problem. In this post we will learn how to configure NGINX to run your Django project.

I assumed that you have already created your project in Django and already run into your parent URL if you have not create project yet please check my this blog Setup Your First Django Project .

I assume that sub path you want is /yourproject/ and all files are present in /home/yourproject/ folder.

Now add it to your NGINX Config: You will find this file into /etc/nginx/sites-available/default.conf location.

This file is a default server configuration file where you add a location variable for your project and static files. This file will automatically load configuration files provided by other applications, such as Drupal or WordPress or Django.

server {
	listen 80;
	listen [::]:80;
	server_name yourmainurl.com;

	location / {
		root /var/www/html;
		try_files $uri $uri/ =404;
	}

	location /yourproject/ {
		proxy_pass http://localhost:6001/;
		proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
	}

	location /yourproject/static/ {
		alias /home/yourproject/static/;
		autoindex on;
	}
}

Then, things we will change in your project’s settings.py:

Add this line : FORCE_SCRIPT_NAME = "yourproject"

Changes into these lines:

STATIC_URL = ‘/yourproject/static/’

STATIC_ROOT = os.path.join(BASE_DIR, ‘yourproject/static/’

That’s it. Go check all absolute paths that you wrote down in your project and you are good.

That is it for today, hope it helps. If you have a better approach to resolve this problem please make a comment in comment section below.

If you like this article, you can buy me a coffee. Thanks!

Configure NGINX to Run Django App in a Sub Path

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to top