Login

minimal nginx conf to split get/post requests

Author:
amitu
Posted:
October 14, 2008
Language:
Python
Version:
1.0
Tags:
middleware nginx loadbalancing master-slave
Score:
2 (after 2 ratings)

After a point the sql server becomes the bottleneck in lots of web application, and to scale, master-slave replication with single master, multiple slave is recommended. This setup with nginx can be used to accomplish traffic distribution between master and slave based on request method.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# inspired by http://weichhold.com/2008/09/12/django-nginx-memcached-the-dynamic-trio/
# /etc/nginx/sites-enabled/default
upstream backend_get {
        server 127.0.0.1:8080 weight=1; 
        # any number of servers can be added here to distribute load. 
}

upstream backend_post {
        server 127.0.0.1:8081 weight=1; 
}

server {
        listen   80;
        server_name  localhost;

        access_log  /var/log/nginx/localhost.access.log;

        location / {
                proxy_read_timeout 300;
                if ($request_method = POST)
                {
                        proxy_pass http://backend_post;
                        break;
                }
                # update: after http://simonwillison.net/2008/Oct/14/django/
                # use master while the cookie lasts 
                if ($http_cookie ~* "force_master=([^;]+)(?:;|$)")
                {
                        proxy_pass http://backend_post;
                        break;
                }
                proxy_pass http://backend_get;
        }
}


# PostCookieMiddleware
class PostCookieMiddleware(object):
    """ cookie force_master to take care of replication lag """
    def process_response(self, request, response):
        if request.method == "POST":
            # for next 10 seconds send all requests for this user to master
            response.set_cookie("force_master", "42", max_age=10)
        return response

More like this

  1. nginx x-accel-redirect protection of static files by sean 7 years, 4 months ago
  2. django on tornado by lawgon 5 years, 6 months ago
  3. Admob Ad Insertion Snippet by johnboxall 6 years, 8 months ago
  4. Effective content caching for mass-load site using redirect feature by nnseva 3 years, 8 months ago
  5. jQuery color picker model field by fneumann 6 years, 3 months ago

Comments

Please login first before commenting.