How to run Django and Wordpress using Nginx and Gu

2020-04-18 07:09发布

问题:

I have a Django app that is running on a domain e.g. www.example.com

I want to create a Wordpress landing page, and point this landing page to the home url www.example.com and the wordpress admin site to www.example.com/admin or www.example.com/wp-admin. All the other URLs should be served by Django.

So, I want:

  • www.example.com -> wordpress
  • www.example.com/admin or www.example.com/wp-admin -> wordpress
  • All the other URLs to be served by Django

Till now, this is my Nginx configuration using Django:

upstream django_server {
    server unix:/path/to/gunicorn.sock fail_timeout=0;
}

server {

    listen   80;
    server_name www.example.com example.com
    client_max_body_size 4G;

    access_log /path/to/nginx-access.log;
    error_log /path/to/nginx-error.log;

    location /static/ {
        alias   /path/to/static/;
    }

    location /media/ {
        alias   /path/to/media/;
    }

    location / {
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $http_host;
        proxy_redirect off;
        if (!-f $request_filename) {
            proxy_pass http://django_server;
            break;
        }
    }

    error_page 500 502 503 504 /500.html;
    location = /500.html {
        root /path/to/static/;
    }
}

Any help would be greatly appreciated.

回答1:

WordPress uses an indeterminate set of URLs and so it is important to have a clear partition between that and the set of URLs available to Django. The best solution is to place WordPress into a subdirectory (which is surprisingly easy).

For example:

server {
    ...
    # existing Django configuration
    ...

    location = / {
        return $scheme://$host/blog/;
    }
    location ^~ /blog {
        alias /path/to/wordpress;

        index index.php;
        if (!-e $request_filename) { rewrite ^ /blog/index.php last; }

        location ~ /wp-content/uploads/ { expires 30d; }

        location ~ \.php$ {
            if (!-f $request_filename) { rewrite ^ /blog/index.php last; }

            include       fastcgi_params;
            fastcgi_param SCRIPT_FILENAME $request_filename;
            ...
        }
        location ~* \.(js|css|png|jpg|jpeg|gif|ico)$ { 
            if (!-f $request_filename) { rewrite ^ /blog/index.php last; }
            expires 30d; 
        }
    }
}

You will need to set the Site and Home URLs. See this document for details.

See this document for more.