CORS issue with Django and React hosted on same server - django

I am having a CORS issue with my Django Rest Framework and React app on the same server. I am running Vagrant with an Ubuntu 18 box and NGINX installed (I am assuming this issue will translate to DigitalOcean) I apologize ahead of time if I am providing too much information. DRF is using Supervisor and Gunicorn is on port 8000. I created my React app using create-react-app. I then used npm run build to create the static files.
NGINX Setup:
React Conf
server {
listen 8080;
server_name sandbox.dev;
root /var/sites/sandbox/frontend/build;
index index.html;
client_max_body_size 4G;
location / {
try_files $uri $uri/ /index.html;
}
Django Conf
upstream sandbox_server {
server unix:/var/tmp/gunicorn_sanbox.sock fail_timeout=0;
}
server {
listen 8000;
server_name api.sandbox.dev;
...
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://sandbox_server;
break;
}
Django Setup:
INSTALLED_APPS = [
...
'rest_framework',
'corsheaders',
'myapp',
]
MIDDLEWARE = [
'corsheaders.middleware.CorsMiddleware',
...
]
I have tried the following with no luck
CORS_ORIGIN_ALLOW_ALL = True
and
CORS_ORIGIN_ALLOW_ALL = False
CORS_ORIGIN_WHITELIST = ('192.168.19.76:8080','localhost:8080',)
React App.js
...
fetch("http://localhost:8000/api/v1/token-auth/", {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({"email":"test#user.com", "password":"testuser"}),
})
So to state the obvious CORS is correct because the Origin is localhost:8080 which is a different port so it sees it as cross origin. I have tried the different settings with cors origin allow, but it is still the same issue every time. Obviously I am doing something wrong, but I can't see it.
My thoughts are
Option 1
proxy pass using the django nginx conf file and do away with the react nginx conf file, but I don't know what affect that might cause in production or if this is a good idea. Is there a better way?
location /api {
proxy_set_header X-Forwarded_for $proxy_add_x_forwarded_for;
proxy_set_header Host $http_host;
proxy_redirect off;
proxy_pass http://sandbox_server;
So finalize my thoughts and my question. After trying the different Django options for CORS I am still getting the CORS error. Why, and is it my NGINX conf files causing it or something else? Will I expect to see this in DigitalOcean?
UPDATE 1
I forgot to add the error. Here is the CORS error
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:8000/api/v1/token-auth/. (Reason: CORS request did not succeed).
For those wanting to know the output from the network tab
Host localhost:8000
Origin http://192.168.19.76:8080
Pragma no-cache
Referer http://192.168.19.76:8080/
UPDATE 2
I did test using curl, and everything returned as expected so I know DRF is working corrently.
curl --data "email=test#user.com&password=testuser" http://localhost:8000/api/v1/token-auth/
FINAL UPDATE
Thanks to paulsm4 for all the help and just plain awesomeness.
So, I did abandon django-cors-headers and rolled my own. To answer paulsm4's question, I do not have add_header 'Access-Control-Allow-Origin' '*'; in the NGINX file although I did think about letting NGINX handle CORS vs Django, but never went that far. #paulsm4, this is the proxy_pass I was talking about. The key was adding this block of code to NGINX for the react portion in conjunction with my middleware.
location /api {
proxy_set_header X-Forwarded_For $proxy_add_x_forwarded_for;
proxy_set_header Host $http_host;
proxy_redirect off;
proxy_pass http://sandbox_server;
The above code by itself worked, but it did not allow me to whitelist any incoming URLs. Creating my own middleware allowed me to whitelist. I have no idea why django-cors-headers or even django-cors-middleware did not work for me. What was strange was that fetch never made it far enough with those two packages to get response headers and an error of any sorts, other than the CORS error I was asking about. With the middleware I wrote, fetch was able to fully make the call, and return some response headers whether it succeeded or failed.
For future reference, I might revisit NGINX and allowing it to handle CORS. Here is a good link
CORS on NGINX
NOTE
To clarify; the only middleware installed besides what Django already includes is the cors middleware. Both Django and React reside on the same server, but with different ports.
api.sandbox.com:8000 is the Django Rest Framework
app.sandbox.com:8080 is the React static files
Django 2.0.2
Python 3.6
django-cors-headers 2.4.0
Vagrant/VirtualBox Ubuntu 18.04
NGINX
Django settings.py
INSTALLED_APPS = [
...
# Third Party
'rest_framework',
'corsheaders',
# My Apps
'account',
]
MIDDLEWARE = [
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware',
...
'django.middleware.csrf.CsrfViewMiddleware',
'corsheaders.middleware.CorsPostCsrfMiddleware',
...
]
CORS_ORIGIN_WHITELIST = (
'null',
'192.168.19.76:8080',
'localhost:8080',
'app.sandbox.com:8080'
)
React App.js
fetch("http://localhost:8000/api/v1/token-auth/", {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
"email": "test#user.com",
"password": "testuser"
}),
})
So I am at wits end here. It is either django-cors-headers that is not working or it could possibly be NGINX.

We've been exchanging comments; here's my current understanding:
PROBLEM: You have have a Django back-end API (on port 8080) and a React Front end (on port 8000). Both are currently running on localhost, but will ultimately reside on DigitalOcean. The React client is getting Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:8000/api/v1/token-auth/. (Reason: CORS request did not succeed).
You need to configure CORS.
The request headers in the HTTP traffic you've captured clearly shows this isn't happening yet.
Some relevant links include:
django-cors-headers not work
Handling CORS in Django REST Framework
Djgano REST Framework: CORS
SUGGESTED NEXT STEP:
If you haven't already, please install and configure django-cors-headers

Related

Nginx responds 404 not found on Django media URL in preprod, dev ok

I have a quite standard Django application with a Vuejs frontend.
I have different environments (preprod/dev) in which I have file upload/download features.
For files, everything works fine because they are returned through standard API views in attachment (Content-Disposition: attachment). When it comes to images though, like profile pictures, there is a problem.
In development (DEBUG=True), I have this :
from django.conf import settings
from django.conf.urls.static import static
from django.urls import include, path
from backend.applications.base.views.authentication_views import LoginAPIView, LogoutAPIView
urlpatterns = [
path("api/login", LoginAPIView.as_view()),
path("api/logout", LogoutAPIView.as_view()),
path("api/base/", include("backend.applications.base.urls")),
path("api/contact/", include("backend.applications.contact.urls")),
path("api/helpdesk/", include("backend.applications.helpdesk.urls")),
path("api/inventory/", include("backend.applications.inventory.urls")),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) # For serving media files when DEBUG=True
and images are correctly served (no nginx in dev mode, just frontend and backend dev servers django's runserver).
My preprod however, is made of a nginx container which serves my built vuejs frontend, and a backend container which contains my Django (DEBUG=False) application (which runs with gunicorn this time, like this : gunicorn backend.wsgi:application --bind 0.0.0.0:8000 --access-logfile="-").
Before trying to serve images, I had this nginx configuration :
http {
client_max_body_size 5M;
upstream backend_api {
server backend:8000;
# 'backend' is the name of the backend service in my docker-compose config
}
server {
listen 80;
include /etc/nginx/mime.types;
root /usr/share/nginx/html;
index index.html;
location = /favicon.ico {
access_log off;
log_not_found off;
}
location /api {
proxy_pass http://backend_api;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-Proto $http_x_forwarded_proto;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_redirect off;
}
location / {
try_files $uri $uri/ /index.html;
}
}
}
Then I thought that /media requests should also be passed to the backend and I changed
location /api
into
location ~ ^/(api|media)/ {
My /api URLs are still handled correctly but /media URLs are answered by a 404 :
(trying to load profile pictures of my user(s) in a kanban view).
Also trying directly http://localhost/media/base/users/8/picture.jpg directly in my browser doesn't work :
From here I don't know what to do to solve the issue. If something is missing, mention it and I'll update the post.
Django does not serve static- and media files with runserver, you will need WhiteNoise for that. See http://whitenoise.evans.io/en/stable/
Whitenoise however is not suitable for serving user-uploaded media files. See http://whitenoise.evans.io/en/stable/django.html#serving-media-files
(Optionally, skip whitenoise, and host static/media files through NGINX.)
You really shouldn't be hosting your server with py manage.py runserver. This is not secure. See Why not use "runserver" for production at Django? and https://docs.djangoproject.com/en/dev/ref/django-admin/#runserver
Use something like Gunicorn instead.
See https://docs.djangoproject.com/en/4.1/howto/deployment/wsgi/gunicorn/
(Or waitress, the windows alternative)
https://pypi.org/project/django-waitress/
To host static/media files with nginx, paste this into your nginx conf:
location /media {
alias /PATH/TO/DIRECTORY; #Absolute path.
}
And in your settings.py, set the media root to that same directory.

CORS error while consuming calling REST API with React

I created a restful api with django-rest-framework accessible with this URL http://192.168.33.10:8002/scenarios/ and I'm creating a React app to make calls to the api an d consume its data.
I'm using fetch to make calls to the api
componentWillMount: function(){
this.setState({Problemstyle: this.props.Problemstyle})
fetch('http://192.168.33.10:8002/scenarios/')
.then(result=>result.json())
.then(result=> {
this.steState({items:result})
})
},
when i run my app i get an error in my browser
Fetch API cannot load http://192.168.33.10:8002/scenarios/. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://192.168.33.10:8001' is therefore not allowed access. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
I'm not sure on how to solve this problem as i'm just starting to use React
Please Note: This solution is not for production configuration. This is merely a workaround for easier setup while development. Please refrain from using this in production configuration.
Install django-cors-headers through pip install django-cors-headers
Then, add in installed apps 'corsheaders'.
Add the setting,
CORS_ORIGIN_ALLOW_ALL = True
and,
ALLOWED_HOSTS = ['*']
This should do the trick.
UPDATE
You'll also need to add it to the middlewares,
MIDDLEWARE = [ # Or MIDDLEWARE_CLASSES on Django < 1.10
...
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware',
...
]
The currently accepted answer potentially opens sites up to security risks:
Why does the error happen:
In order for your AJAX request to work well, there are two things that need to happen:
The request has to be accepted by the server.
The returned request must be accepted by the browser, so that the client-side can do something with it.
The error that the OP reports, indicates that the second part of this process is failing. This is because if the request is sent from domain that is different to the server returning the request, the browser won't accept it unless the appropriate headers are set (that is, the server has given permission for the browser to read it).
How to fix it:
Now to fix this, we can use django-cors-headers. This will add the apropriate headers, so that the browser accepts the returned response. To install run:
pip install django-cors-headers
and add it to your middleware:
MIDDLEWARE = [
...
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware',
...
]
Now, you need to add the domain you are sending your AJAX request from, to the list of allowed domains:
CORS_ALLOWED_ORIGINS = [
"www.example.com",
"http://127.0.0.1:8000",
...
]
What about CORS_ORIGIN_ALLOW_ALL?
Do not use this unless you have a specific need to. Setting this to true, will mean that, any origin will be able to make a request to your API, and get a response. Unless you are making a public API, you probably won't need to do this. More likely you will only need to serve a single domain or a few domains (maybe you have a front-end, served from a different place to your API etc.)
If you are happy for any domain to access your API then you can set the following:
CORS_ORIGIN_ALLOW_ALL = True
If you do this, you will also need to set the following:
ALLOWED_HOSTS = ['*']
The reason for this, is Django will only accept certain hosts by default, so there's no point setting CORS_ORIGIN_ALLOW_ALL = True unless you're actually going to accept requests from anyone (that is the part 1 in the explanation above).
Note that by setting allowed hosts to a wildcard, you open yourself up to HTTP host header attacks. Make sure you understand these, and have made sure you are not affected. You can read more about them in the django docs.
Also note: if you have not set your ALLOWED_HOSTS and you are wondering why your requests are working, it is because when DEBUG=True certain hosts are allowed automatically, http://127.0.0.1:8000 etc.
Using django-cors-headers
Start by installing django-cors-headers using pip
pip install django-cors-headers
You need to add it to your project settings.py file:
INSTALLED_APPS = (
##...
'corsheaders'
)
Next you need to add corsheaders.middleware.CorsMiddleware middleware to the middleware classes in settings.py
MIDDLEWARE_CLASSES = (
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.BrokenLinkEmailsMiddleware',
'django.middleware.common.CommonMiddleware',
#...
)
You can then, either enable CORS for all domains by adding the following setting
CORS_ORIGIN_ALLOW_ALL = True
Or Only enable CORS for specified domains:
CORS_ORIGIN_ALLOW_ALL = False
CORS_ORIGIN_WHITELIST = (
'http//:localhost:8000',
)
See Yinon_90's answer for a better working version of this concept.
I wanted to propose a solution that does not require altering the behavior of the Django or React apps.
In production, you might want to serve both apps on the same domain/from the same server, under different paths. This wouldn't cause any CORS conflict in production.
Of course, we want to debug Django and utilize React HMR & Dev tools while debugging. For this, I've spun up an nginx docker container:
docker-compose.yml:
version: '3.8'
services:
web:
image: nginx:latest
ports:
- 8080:80
volumes:
- ./nginx.conf:/etc/nginx/nginx.conf:ro
command: [nginx-debug, '-g', 'daemon off;']
environment:
- NGINX_HOST=localhost
- NGINX_PORT=80
nginx.conf:
Django debug is on port 8000, React HMR is on port 3000. I've allowed three paths to go to the Django app, /accounts, /api, and /admin. The rest goes to the React app (and into the React Router system)
events {}
http{
server {
listen 80;
server_name localhost;
location ~* /(accounts|api|admin) {
proxy_pass http://host.docker.internal:8000;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
location / {
proxy_pass http://host.docker.internal:3000;
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "Upgrade";
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
}
}
After docker-compose up, manage.py runserver, and npm start, both apps are available at localhost:8000!
UPDATE (12.12.22)
Just add to the package.json file the following line:
"proxy": "http://localhost:8000"
OLD ANSWER
Based on Joe Sadoski's great idea,
I suggest an improvement to his solution that also supports react hot-reload-on-changes:
(All other proposed solutions here do not work in chrome since the last upgrades in 2022)
version: '3.1'
services:
web:
image: nginx:latest
ports:
- 8080:80
volumes:
- ./nginx.conf:/etc/nginx/nginx.conf:ro
command: [nginx-debug, '-g', 'daemon off;']
environment:
- NGINX_HOST=localhost
- NGINX_PORT=80
network_mode: host
restart: unless-stopped
My change here is: network_mode: host
Now the nginx.conf looks like this:
events {}
http{
server {
listen 80;
server_name localhost;
// this block handle react hot-reload
location /sockjs-node {
proxy_pass http://localhost:3000;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
}
// this block handle API calls
location ~* /(accounts|api|admin) {
proxy_pass http://localhost:8000;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
// this block handle all the rest (react/statics...)
location / {
proxy_pass http://localhost:3000;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
}
}
Here I change the upstreams to point on localhost so both react server and django should run on the host computer in ports 3000 and 8000.
So, after docker-compose up, manage.py runserver, and npm start, both apps are available at http://localhost!

Invalid HTTP_HOST header: 'localhost:90,localhost:90'. The domain name provided is not valid according to RFC 1034/1035

I am trying to configure nginx along with Gunicorn for a Django project. nginx is giving me the following error:
DisallowedHost at /
Invalid HTTP_HOST header: 'localhost:90,localhost:90'. The domain name provided is not valid according to RFC 1034/1035.
This is my nginx configuration
server {
listen 90;
listen [::]:90;
server_name xxxx;
location = /favicon.ico { access_log off; log_not_found off; }
location /static/ {
root /home/user/djangopro/djangoapp;
}
location / {
include proxy_params;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $http_host;
proxy_buffering off;
proxy_redirect off;
proxy_pass http://localhost:8200/;
}
}
Gunicorn is serving the site properly at localhost:8200. Can anyone tell me what is causing the error?
I was getting the same error. I'm guessing you might be coming from Flask converting to Django? If you remove the proxy_set_header Host $http_host; line from your configuration, it should work (it fixed my error). I think what that does is stack together both the requesting ip address, and the proxy ip address, while Django only wants a single ip address, not a list. See this Django ticket: https://code.djangoproject.com/ticket/28028
I'm guessing you already got this figured out (since its been a few months), but I'm still answering to save someone the 2 hours I just spent googling :)
edit: I'd like to clarify, the problem comes from having both include proxy_params; and proxy_set_header Host $http_host; set. The default proxy_params already have the proxy_set_header Host $http_host; included, so it'll set the host twice, hence the list of two hosts. Look at the proxy_params file in /etc/nginx/proxy_params if you're on Ubuntu (will be a similar path on other machines).
I came across a similar issue with docker because I'm trying to call a django service from another container.
Ended up doing a monkey patch in settings.py since all this method does is actually check / match the domain. Could be a security issue, do at your own risk.
# monkey patch to get rid of message below in docker
from django.http.request import HttpRequest
HttpRequest.get_host = HttpRequest._get_raw_host
I had this problem, too, and discovered that Django actually has a reference to it, buried obscurely in its docs.
The solution is to implement a custom middleware, though in my case I had to modify the middleware suggested in the docs. Here is my modified middleware, and the line in settings.py where I added it:
custom.middleware.py:
class MultipleProxyMiddleware:
FORWARDED_FOR_FIELDS = [
'HTTP_X_FORWARDED_FOR',
'HTTP_X_FORWARDED_HOST',
'HTTP_X_FORWARDED_SERVER',
'HTTP_HOST' <=== I ADDED THIS LINE
]
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
"""
Rewrites the proxy headers so that only the most
recent proxy is used.
"""
for field in self.FORWARDED_FOR_FIELDS:
if field in request.META:
if ',' in request.META[field]:
parts = request.META[field].split(',')
request.META[field] = parts[-1].strip()
return self.get_response(request)
settings.py:
MIDDLEWARE = [
'my.apps.custom.middleware.MultipleProxyMiddleware', <=== I added this line
'corsheaders.middleware.CorsMiddleware',
'django.middleware.security.SecurityMiddleware',
'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',
'axes.middleware.AxesMiddleware',
]

How to deploy django on VPS with external subdomain.?

Good day.
I have a web app that I have developed using django. I tested fine on my local, and I'm happy with how it works.
However I'm facing an issue bringing it online I used those two guides to reach my deployment:
https://www.digitalocean.com/community/tutorials/how-to-set-up-django-with-postgres-nginx-and-gunicorn-on-ubuntu-16-04
and
http://michal.karzynski.pl/blog/2013/06/09/django-nginx-gunicorn-virtualenv-supervisor/
However my page is giving me a forbidden page.
I suspect my issue is with the way I'm handling the subdomain. So the site . has been developed using php, and I have worked on my part with django and been provided with a subdomain which is member.domain.com, So I'm deploying it on the VPS and have to make it use the subdomain.
This is how my allowed hosts looks in the settings.py
ALLOWED_HOSTS = ['member.domain.com']
and
in my nginx:
upstream app_server {
# fail_timeout=0 means we always retry an upstream even if it failed
# to return a good HTTP response (in case the Unicorn master nukes a
# single worker for timing out).
server unix:/home/path/project/run/gunicorn.sock fail_timeout=0;
}
server {
listen 80;
server_name member.domain.com;
client_max_body_size 4G;
access_log /home/path/project/logs/nginx-access.log;
error_log /home/path/project/logs/nginx-error.log;
location /static/ {
alias /home/path/project/src/static/;
}
location /media/ {
alias /home/path/project/src/media/;
}
location / {
# an HTTP header important enough to have its own Wikipedia entry:
# http://en.wikipedia.org/wiki/X-Forwarded-For
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
# enable this if and only if you use HTTPS, this helps Rack
# set the proper protocol for doing redirects:
# proxy_set_header X-Forwarded-Proto https;
# pass the Host: header from the client right along so redirects
# can be set properly within the Rack application
proxy_set_header Host $http_host;
# we don't want nginx trying to do something clever with
# redirects, we set the Host: header above already.
proxy_redirect off;
# set "proxy_buffering off" *only* for Rainbows! when doing
# Comet/long-poll stuff. It's also safe to set if you're
# using only serving fast clients with Unicorn + nginx.
# Otherwise you _want_ nginx to buffer responses to slow
# clients, really.
# proxy_buffering off;
# Try to serve static files from nginx, no point in making an
# *application* server like Unicorn/Rainbows! serve static files.
if (!-f $request_filename) {
proxy_pass http://app_server;
break;
}
}
# Error pages
error_page 502 503 504 /500.html;
location = /500.html {
root /home/path/project/src/static/;
}
}
I'm not sure what I am doing wrong.
I will appreciate any help
To respond to 'example.com' and any subdomains, start the domain with a dot
ALLOWED_HOSTS = ['.example.com', '203.0.113.5']
I didn't even try how to run django on subdomains, but from article link you shared, you missed some configuration in your settings.py
ALLOWED_HOSTS = ['member.domain.com']
Changed
ALLOWED_HOSTS = ['.domain.com']
Hope this will solve your problem

Using Django, switched from heroku + gunicorn to digitalocean + nginx + gunicorn, site now broken

I had my django app on heroku for a while with no problems. I now want to move it to a digital ocean droplet, partly as a learning exercise, partly for scalability (and cost) reasons.
After following this excellent tutorial almost to the letter, the app is working but with a huge gotcha: I now get an infinite redirect loop when I try to log in to the admin site. The first request is a POST ?next=/admin/ with the username and password, this gets a 302 response to redirect to GET /admin/, which gets a 302 response redirect to ?next=/admin/, and so on.
I have spent 2 or 3 hours with google and various nginx tutorials and this is the first time my "google the error message, copy and paste random code snippets, repeat" algorithm has ever failed me, I'm hoping the reason is that the error is trivial to solve and I just can't see it?
If it's not trivial to solve, let me know and I'll post more info.
Thanks in advance
edit 1: my nginx config file for the app is basically a verbatim copy of the tutorial. It looks like this:
upstream hello_app_server {
# fail_timeout=0 means we always retry an upstream even if it failed
# to return a good HTTP response (in case the Unicorn master nukes a
# single worker for timing out).
server unix:/webapps/hello_django/run/gunicorn.sock fail_timeout=0;
}
server {
listen 80;
server_name example.com;
client_max_body_size 4G;
access_log /webapps/hello_django/logs/nginx-access.log;
error_log /webapps/hello_django/logs/nginx-error.log;
location /static/ {
alias /webapps/hello_django/static/;
}
location /media/ {
alias /webapps/hello_django/media/;
}
location / {
# an HTTP header important enough to have its own Wikipedia entry:
# http://en.wikipedia.org/wiki/X-Forwarded-For
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
# enable this if and only if you use HTTPS, this helps Rack
# set the proper protocol for doing redirects:
# proxy_set_header X-Forwarded-Proto https;
# pass the Host: header from the client right along so redirects
# can be set properly within the Rack application
proxy_set_header Host $http_host;
# we don't want nginx trying to do something clever with
# redirects, we set the Host: header above already.
proxy_redirect off;
# set "proxy_buffering off" *only* for Rainbows! when doing
# Comet/long-poll stuff. It's also safe to set if you're
# using only serving fast clients with Unicorn + nginx.
# Otherwise you _want_ nginx to buffer responses to slow
# clients, really.
# proxy_buffering off;
# Try to serve static files from nginx, no point in making an
# *application* server like Unicorn/Rainbows! serve static files.
if (!-f $request_filename) {
proxy_pass http://hello_app_server;
break;
}
}
# Error pages
error_page 500 502 503 504 /500.html;
location = /500.html {
root /webapps/hello_django/static/;
}
}