Question

Integrating OpenResty with a Django application using Nginx

This is a continuation of

https://www.digitalocean.com/community/questions/nginx-and-openresty

Integrating OpenResty with a Django application using Nginx can enhance your web application’s capabilities, allowing you to leverage Lua scripting for advanced features while maintaining the robustness of your Django backend. Here’s a step-by-step guide on how to set up OpenResty with a Django application:


Submit an answer


This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

Sign In or Sign Up to Answer

These answers are provided by our Community. If you find them useful, show some love by clicking the heart. If you run into issues leave a comment, or add your own answer to help others.

KFSys
Site Moderator
Site Moderator badge
July 21, 2024
Accepted Answer

Step 1: Set Up Your Django Application

Ensure your Django application is running and accessible. You can start your Django development server using:

python manage.py runserver

For production, you should use a WSGI server like Gunicorn:

pip install gunicorn gunicorn myproject.wsgi:application

Step 2: Configure Nginx with OpenResty

Create or modify your Nginx configuration file to integrate OpenResty with your Django application. Here’s an example configuration:

worker_processes  1;

events {
    worker_connections  1024;
}

http {
    include       mime.types;
    default_type  application/octet-stream;

    # Define upstream Django server
    upstream django_server {
        server 127.0.0.1:8000;  # Gunicorn server address
    }

    server {
        listen 80;
        server_name your_domain.com;

        # Static files
        location /static/ {
            alias /path/to/your/static/files/;
        }

        # Media files
        location /media/ {
            alias /path/to/your/media/files/;
        }

        # Root location
        location / {
            proxy_pass http://django_server;
            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;
        }

        # Example of using Lua scripting
        location /lua {
            default_type 'text/plain';
            content_by_lua_block {
                ngx.say("Hello from OpenResty with Django!")
            }
        }

        # Example of custom authentication using Lua
        location /protected {
            access_by_lua_block {
                local token = ngx.var.arg_token
                if token ~= "your_secret_token" then
                    ngx.status = ngx.HTTP_UNAUTHORIZED
                    ngx.say("Unauthorized")
                    ngx.exit(ngx.HTTP_UNAUTHORIZED)
                end
            }
            proxy_pass http://django_server;
        }
    }
}

Explanation

  • upstream django_server: Defines the Django application server running on Gunicorn.
  • location /static/ and location /media/: Serves static and media files.
  • location /: Proxies requests to the Django application.
  • location /lua: Demonstrates a simple Lua script.
  • location /protected: Shows custom authentication using Lua.

Step 3: Test and Reload Nginx

Test your Nginx configuration:

sudo nginx -t

If the test is successful, reload Nginx to apply the changes:

sudo service nginx restart

Step 4: Configure Django for Static and Media Files

Ensure your Django settings are configured to collect static files and serve media files. Update your settings.py:

# settings.py

import os

# Static files (CSS, JavaScript, Images)
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')

# Media files (Uploaded by users)
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

Collect static files:

python manage.py collectstatic

Step 5: Run Gunicorn and Nginx

Start your Gunicorn server:

gunicorn myproject.wsgi:application

Additional Enhancements

  • Security: Consider using HTTPS by configuring SSL/TLS with Nginx.
  • Performance: Use caching strategies with OpenResty and optimize your Django application.
  • Monitoring: Implement monitoring tools to keep track of your application’s performance and health.

Conclusion

By integrating OpenResty with Nginx and your Django application, you can leverage the power of Lua scripting to enhance your web application’s capabilities. This setup provides a flexible and powerful environment for developing high-performance, secure, and scalable web applications.

Become a contributor for community

Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

DigitalOcean Documentation

Full documentation for every DigitalOcean product.

Resources for startups and SMBs

The Wave has everything you need to know about building a business, from raising funding to marketing your product.

Get our newsletter

Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.

New accounts only. By submitting your email you agree to our Privacy Policy

The developer cloud

Scale up as you grow — whether you're running one virtual machine or ten thousand.

Get started for free

Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

*This promotional offer applies to new accounts only.