500 error on displayable_links.js in django, mezzanine, nginx - django

I am getting a 500 error on displayable_links.js. I assume it is something with my ssl setup. Using Django 1.9.1, Python 2.7.5, PostgreSQL 9.2.14, and Mezzanine 4.1. Happens in debug and behind gunicorn. I have * for allowed hosts just to eliminate that as a possibility. It also happens directly over port 8000.
My nginc.conf:
worker_processes 1;
error_log /var/log/nginx/error.log;
error_log /var/log/nginx/error.log notice;
error_log /var/log/nginx/error.log info;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
keepalive_timeout 65;
server {
listen 80 default_server;
root /opt/www/;
return 301 https://www2.example.com$request_uri;
gzip on;
gzip_disable "msie6";
gzip_vary on;
gzip_proxied any;
gzip_comp_level 6;
gzip_buffers 16 8k;
gzip_http_version 1.1;
gzip_types text/plain text/css application/json application/x-javascript text/xml application/xml application/xml+rss text/javascript;
}
server {
listen 443 ssl;
server_name www2.example.com;
add_header X-Frame-Options SAMEORIGIN;
server_name_in_redirect off;
root /opt/www/;
gzip off;
gzip_disable "msie6";
gzip_vary on;
gzip_proxied any;
gzip_comp_level 6;
gzip_buffers 16 8k;
gzip_http_version 1.1;
gzip_types text/plain
text/css
application/json
application/javascript
application/x-javascript
text/xml
application/xml
application/xml+rss
text/javascript;
ssl_certificate /etc/httpd/conf.d/2016.example.com.crt;
ssl_certificate_key /etc/httpd/conf.d/2016.example.com.key;
ssl_trusted_certificate /etc/httpd/conf.d/intermediate.crt;
ssl_dhparam /etc/httpd/conf.d/dhparams.pem;
add_header Strict-Transport-Security max-age=31536000;
ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
ssl_ciphers 'EECDH+AESGCM:EDH+AESGCM:AES256+EECDH:AES256+EDH';
ssl_buffer_size 8k;
ssl_session_cache shared:SSL:30m;
ssl_session_timeout 30m;
ssl_stapling on;
resolver 8.8.8.8;
ssl_stapling_verify on;
ssl_prefer_server_ciphers on;
proxy_redirect off;
location / {
proxy_pass http://127.0.0.1:8000;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
location /static/ {
autoindex on;
root /opt/www/;
}
}
}
And my settings.py:
from __future__ import absolute_import, unicode_literals
enter code here`enter code here`import os
from django.utils.translation import ugettext_lazy as _
SEARCH_MODEL_CHOICES = []
PAGE_MENU_TEMPLATES = (
(1, _("Top navigation bar"), "pages/menus/dropdown.html"),
(2, _("Left-hand tree"), "pages/menus/tree.html"),
(3, _("Footer"), "pages/menus/footer.html"),
)
PAGE_MENU_TEMPLATES_DEFAULT = (2,)
USE_MODELTRANSLATION = False
ALLOWED_HOSTS = ['*']
SERVER_EMAIL = 'server#example.com'
ADMINS = [('example', 'example#example.com'),]
TIME_ZONE = 'UTC'
USE_TZ = True
LANGUAGE_CODE = "en"
LANGUAGES = (
('en', _('English')),
)
SITE_TITLE = "example Systems"
DEBUG = False
SESSION_EXPIRE_AT_BROWSER_CLOSE = True
SITE_ID = 1
USE_I18N = False
AUTHENTICATION_BACKENDS = ("mezzanine.core.auth_backends.MezzanineBackend",)
FILE_UPLOAD_PERMISSIONS = 0o644
DATABASES = {
"default": {
"ENGINE": "django.db.backends.postgresql",
"NAME": "example",
"USER": "example",
"PASSWORD": "example",
"HOST": "127.0.0.1",
"PORT": "5432",
}
}
PROJECT_APP_PATH = os.path.dirname(os.path.abspath(__file__))
PROJECT_APP = os.path.basename(PROJECT_APP_PATH)
PROJECT_ROOT = BASE_DIR = os.path.dirname(PROJECT_APP_PATH)
CACHE_MIDDLEWARE_KEY_PREFIX = PROJECT_APP
STATIC_URL = "https://www2.example.com/static/"
STATIC_ROOT = "/opt/www/static/"
MEDIA_URL = STATIC_URL + "media/"
MEDIA_ROOT = os.path.join(PROJECT_ROOT, *MEDIA_URL.strip("/").split("/"))
ROOT_URLCONF = "%s.urls" % PROJECT_APP
TEMPLATES = [{u'APP_DIRS': True,
u'BACKEND': u'django.template.backends.django.DjangoTemplates',
u'DIRS': (u'/opt/www/modernbiz/theme/templates', u'/opt/www/templates'),
u'OPTIONS': {u'builtins': [u'mezzanine.template.loader_tags'],
u'context_processors': (u'django.contrib.auth.context_processors.auth',
u'django.contrib.messages.context_processors.messages',
u'django.core.context_processors.debug',
u'django.core.context_processors.i18n',
u'django.core.context_processors.static',
u'django.core.context_processors.media',
u'django.core.context_processors.request',
u'django.core.context_processors.tz',
u'mezzanine.conf.context_processors.settings',
u'mezzanine.pages.context_processors.page')}}]
INSTALLED_APPS = (
"modernbiz",
"django.contrib.admin",
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.redirects",
"django.contrib.sessions",
"django.contrib.sites",
"django.contrib.sitemaps",
"django.contrib.staticfiles",
"mezzanine.boot",
"mezzanine.conf",
"mezzanine.core",
"mezzanine.generic",
"mezzanine.pages",
"mezzanine.blog",
"mezzanine.forms",
"mezzanine.galleries",
"mezzanine.twitter",
"howtos",
"mezzanine.accounts",
"mezzanine.mobile",
"polls",
)
MIDDLEWARE_CLASSES = (
"django.middleware.gzip.GZipMiddleware",
'htmlmin.middleware.MarkRequestMiddleware',
"mezzanine.core.middleware.UpdateCacheMiddleware",
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
"mezzanine.core.request.CurrentRequestMiddleware",
"mezzanine.core.middleware.RedirectFallbackMiddleware",
"mezzanine.core.middleware.TemplateForDeviceMiddleware",
"mezzanine.core.middleware.TemplateForHostMiddleware",
"mezzanine.core.middleware.AdminLoginInterfaceSelectorMiddleware",
"mezzanine.core.middleware.SitePermissionMiddleware",
"mezzanine.pages.middleware.PageMiddleware",
"mezzanine.core.middleware.FetchFromCacheMiddleware",
)
PACKAGE_NAME_FILEBROWSER = "filebrowser_safe"
PACKAGE_NAME_GRAPPELLI = "grappelli_safe"
OPTIONAL_APPS = (
"debug_toolbar",
"django_extensions",
"compressor",
PACKAGE_NAME_FILEBROWSER,
PACKAGE_NAME_GRAPPELLI,
)
f = os.path.join(PROJECT_APP_PATH, "local_settings.py")
if os.path.exists(f):
exec(open(f, "rb").read())
try:
from mezzanine.utils.conf import set_dynamic_settings
except ImportError:
pass
else:
set_dynamic_settings(globals())
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTOCOL', 'https')
COMPRESS_ENABLED = True
COMPRESS_OFFLINE = True
LOGGING = {
'version': 1,
'disable_existing_loggers': True,
'formatters': {
'verbose': {
'format': '%(asctime)s %(levelname)s [%(name)s:%(lineno)s] %(module)s %(process)d %(thread)d %(message)s'
}
},
'handlers': {
'file': {
'level': 'DEBUG',
'class': 'logging.FileHandler',
'formatter': 'verbose',
'filename': '/var/log/gunicorn/gunicorn.errors',
}
},
'loggers': {
'django.errors': {
'level': 'DEBUG',
'handlers': ['file'],
'propagate': True,
},
}
}
Edited to add the stacktrace:
Internal Server Error: /displayable_links.js
Traceback (most recent call last):
File "/usr/lib/python2.7/site-packages/django/core/handlers/base.py", line 149, in get_response
response = self.process_exception_by_middleware(e, request)
File "/usr/lib/python2.7/site-packages/django/core/handlers/base.py", line 147, in get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/usr/lib64/python2.7/site-packages/mezzanine/core/views.py", line 192, in displayable_links_js
for url, obj in Displayable.objects.url_map(for_user=request.user).items():
File "/usr/lib64/python2.7/site-packages/mezzanine/core/managers.py", line 366, in url_map
home = self.model(title=_("Home"))
File "/usr/lib/python2.7/site-packages/django/db/models/base.py", line 408, in __init__
val = field.get_default()
File "/usr/lib/python2.7/site-packages/django/db/models/fields/related.py", line 902, in get_default
if isinstance(field_default, self.remote_field.model):
TypeError: isinstance() arg 2 must be a class, type, or tuple of classes and types
[01/Feb/2016 20:50:25] "GET /displayable_links.js HTTP/1.0" 500 6309

It has been fixed a few days ago after the 4.1 release. So you need to use the master branch for now until 4.1.1 or 4.2.
https://github.com/stephenmcd/mezzanine/pull/1516

I just resolved this issue with a little hack. All you need is to override the handler of URL endpoint: "^displayable_links.js$" inside your app's urls.py file. Here is what I did:
Create a custom views.py to store your custom handler function:
from django.http import (HttpResponse)
from json import dumps
def editor_link_handler(request):
links = []
sorted_links = sorted(links, key=lambda link: (link[0], link[1]['value']))
return HttpResponse(dumps([link[1] for link in sorted_links]))
Then, inside your own app's urls.py file. Here is an example code snippet which works for me now:
# urls.py // Skip to the "Important" section for my custom code
from __future__ import unicode_literals
from django.conf.urls import include, url
from django.conf.urls.i18n import i18n_patterns
from django.contrib import admin
from django.views.i18n import set_language
import mezzanine
from mezzanine.core.views import direct_to_template
from mezzanine.conf import settings
from mezzanine.blog.views import blog_post_list
############################
### Important #########
##### Here is my cusom view function to handle the request
##############
from views import editor_link_handler
urlpatterns = i18n_patterns(
# Change the admin prefix here to use an alternate URL for the
# admin interface, which would be marginally more secure.
url("^admin/", include(admin.site.urls)),
)
##################
###Important:#######
##### Here comes the serious stuff (my custom code)
###############
urlpatterns += [
url("^displayable_links.js$", editor_link_handler,
name="editor_link_handler"),
]
Remember this url rule needs to be anywhere BEFORE you do:
url("^", include("mezzanine.urls")),
Because in Django URL dispatchers, ordering does matter!
If you did this as instructed, when you click the "add link" button in TinyMCE, it will be handled by your custom handler, and you should be able to add links to your blog/page without a problem.
NOTE:
This is nothing more than a hack, please comment below if this doesn't work for you or that you have a better solution.

Related

Django static are not getting load on AWS using Nginx

i have a website build on Django. everything is working fine on local machine but the static file are not getting load on production. Django project is running fine on Debug=False I did install
whitenoise==6.2.0
the error
django settings
SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False
ALLOWED_HOSTS = ["*"]
CORS_ALLOW_CREDENTIALS = True
CORS_ORIGIN_ALLOW_ALL = True
CORS_ALLOW_CREDENTIALS = True
CORS_ALLOWED_ORIGINS = [
"http://54.234.143.251",
]
CSRF_TRUSTED_ORIGINS = [
"http://54.234.143.251",
]
# Application definition
INSTALLED_APPS = [
"django.contrib.admin",
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sessions",
"django.contrib.messages",
"django.contrib.staticfiles",
# app
"applipsync",
"store",
# packages
"whitenoise.runserver_nostatic",
"rest_framework",
"django_q",
"allauth",
"allauth.account",
"allauth.socialaccount",
"crispy_forms",
]
CRISPY_TEMPLATE_PACK = "bootstrap4"
MIDDLEWARE = [
"django.middleware.security.SecurityMiddleware",
"whitenoise.middleware.WhiteNoiseMiddleware", #add whitenoise
"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",
]
ROOT_URLCONF = "core.urls"
TEMPLATES = [
{
"BACKEND": "django.template.backends.django.DjangoTemplates",
"DIRS": [BASE_DIR / "templates"],
"APP_DIRS": True,
"OPTIONS": {
"context_processors": [
"django.template.context_processors.debug",
"django.template.context_processors.request",
"django.contrib.auth.context_processors.auth",
"django.contrib.messages.context_processors.messages",
],
},
},
]
WSGI_APPLICATION = "core.wsgi.application"
# EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
ACCOUNT_EMAIL_REQUIRED = True
# Make email verification mandatory to avoid junk email accounts
ACCOUNT_EMAIL_VERIFICATION = "mandatory"
EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend"
EMAIL_HOST = "smtp.gmail.com"
EMAIL_USE_TLS = True
EMAIL_PORT = 587
EMAIL_HOST_USER = ""
EMAIL_HOST_PASSWORD = ""
AUTHENTICATION_BACKENDS = [
# Needed to login by username in Django admin, regardless of `allauth`
"django.contrib.auth.backends.ModelBackend",
# `allauth` specific authentication methods, such as login by e-mail
"allauth.account.auth_backends.AuthenticationBackend",
]
LOGIN_REDIRECT_URL = "/"
ACCOUNT_LOGIN_ON_EMAIL_CONFIRMATION = True
# Database
# https://docs.djangoproject.com/en/4.1/ref/settings/#databases
DATABASES = {
"default": {
"ENGINE": "django.db.backends.sqlite3",
"NAME": BASE_DIR / "db.sqlite3",
}
}
# Password validation
# https://docs.djangoproject.com/en/4.1/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
"NAME": "django.contrib.auth.password_validation.UserAttributeSimilarityValidator",
},
{
"NAME": "django.contrib.auth.password_validation.MinimumLengthValidator",
},
{
"NAME": "django.contrib.auth.password_validation.CommonPasswordValidator",
},
{
"NAME": "django.contrib.auth.password_validation.NumericPasswordValidator",
},
]
# Internationalization
# https://docs.djangoproject.com/en/4.1/topics/i18n/
LANGUAGE_CODE = "en-us"
TIME_ZONE = "UTC"
USE_I18N = True
USE_TZ = True
# settings.py example
Q_CLUSTER = {
"name": "pdm",
"workers": 1,
"recycle": 500,
"timeout": 60,
"retry": 120,
"compress": True,
"save_limit": 250,
"queue_limit": 500,
"cpu_affinity": 1,
"label": "Django Q",
"daemonize_workers": False,
"orm": "default",
}
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.1/howto/static-files/
# settings.py
STATIC_URL = "static/"
STATICFILES_DIRS = (os.path.join(BASE_DIR, "static"),)
# PROJECT_DIR = os.path.dirname(os.path.abspath(__file__))
# STATIC_ROOT = os.path.join(BASE_DIR, 'static')
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') ##specify static root
print("BASE_DIR ", BASE_DIR)
print("------------------------------------------")
print(STATIC_ROOT)
# Default primary key field type
# https://docs.djangoproject.com/en/4.1/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField"
MEDIA_URL = "/media/"
MEDIA_ROOT = os.path.join(BASE_DIR, "media")
TEMPLATE_DIRS = (
os.path.join(os.path.dirname(__file__), "templates").replace("\\", "/"),
)
path in aws
Nginx configuration
server {
listen 80;
server_name 54.234.143.251;
client_max_body_size 100M;
sendfile on;
# to avoid any error while fetching fevicon
location = /favicon.ico { access_log off;
log_not_found off;
}
location /static/ {
autoindex on;
alias /home/ubuntu/lipsync-website/app/staticfiles/;
}
location /media/ {
autoindex on;
alias /home/ubuntu/lipsync-website/app/media/;
}
location / {
# communicate via socket file created by Gunicorn
# proxy_pass http://unix:/home/ubuntu/lipsync-website/app/core.sock;
proxy_pass http://0.0.0.0:8000;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $host;
proxy_redirect off;
}
}
i did change the path of nginx but still the static files are not getting load on production.

django-private-storage configuration in nginx and Docker

I am trying to use django-private-storage package to protect a model's file from being accessed
or downloaded by users who are not owners of the file.
I was able to do it successfully in development (using python manage.py runserver)
In development, I am using nginx configured via docker.
I can create objects with both FileField and PrivateFileField. My problem is accessing the urls associated with a PrivateFileField.
The mediafiles are being served as expected (e.g. when I access the url of a FileField), but I get a "404 Not Found" error from nginx when I access the url of a PrivateFileField.
My hunch is that the server response is not properly configured to have a 'X-Accel-Redirect' data,
thus treating the response not internal.
If I remove the line "internal;" in my nginx.conf for the private-data location, the PrivateFile is served
properly, although, now, it is not private.
location /private-data/ {
internal; #<------ the PrivateFile can be accessed if this line is removed
alias /home/app/web/private-data/;
}
Also, I am sure that the private file was saved in /home/app/web/private-data
Am I missing out something in the implementation?
Thanks in advance.
Additional info:
nginx version: 1.17.4
django-private-storage version: 2.2.2
My production setup follows this:
https://testdriven.io/blog/dockerizing-django-with-postgres-gunicorn-and-nginx/
FILES -----------------------------------
docker-compose.prod.yml
version: '3.7'
services:
web:
build:
context: ./web_app
dockerfile: Dockerfile.prod
command: gunicorn notify_django_project.wsgi:application --bind 0.0.0.0:8000
volumes:
- static_volume:/home/app/web/staticfiles
- media_volume:/home/app/web/mediafiles
- private_volume:/home/app/web/private-data
expose:
- 8000
env_file:
- ./.env.prod
depends_on:
- db
db:
image: postgres:12.0-alpine
volumes:
- postgres_data:/var/lib/postgresql/data/
env_file:
- ./.env.prod.db
nginx:
build: ./nginx
volumes:
- static_volume:/home/app/web/staticfiles
- media_volume:/home/app/web/mediafiles
- private_volume:/home/app/web/private-data
ports:
- 1337:80
depends_on:
- web
volumes:
postgres_data:
static_volume:
media_volume:
private_volume:
nginx.conf
upstream django_project {
server web:8000;
}
server {
listen 80;
location / {
proxy_pass http://django_project;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $host;
proxy_redirect off;
}
location /staticfiles/ {
alias /home/app/web/staticfiles/;
}
location /mediafiles/ {
alias /home/app/web/mediafiles/;
}
location /private-data/ {
internal;
alias /home/app/web/private-data/;
}
}
settings.py
INSTALLED_APPS = [
...
'private_storage',
....
]
PRIVATE_STORAGE_ROOT = os.path.join(BASE_DIR, "private-data")
PRIVATE_STORAGE_AUTH_FUNCTION = 'private_storage.permissions.allow_authenticated'
PRIVATE_STORAGE_INTERNAL_URL = '/private-data/'
PRIVATE_STORAGE_SERVER = 'nginx'
models.py
class Message(models.Model):
id = models.UUIDField(
primary_key=True,
default=uuid.uuid4,
editable=False)
subject = models.CharField(max_length=255)
attachment = models.FileField(upload_to=get_attachment_save_path, null=True, blank=True)
private_attachment = PrivateFileField(upload_subfolder=get_private_attachment_save_path, null=True, blank=True)
urls.py
urlpatterns = [
...
path('private-data/<str:code>/<int:year>/<str:subdir>/<uuid:pk>/<str:filename>', DownloadPrivateFileView.as_view(), name="file_download"),
url('^private-data/', include(private_storage.urls)),
...
]
views.py
#method_decorator(login_required, name='dispatch')
class DownloadPrivateFileView(PrivateStorageDetailView):
model = Message
model_file_field = 'private_attachment'
def can_access_file(self, private_file):
# When the object can be accessed, the file may be downloaded.
# This overrides PRIVATE_STORAGE_AUTH_FUNCTION
# grant_access checks private_file ownership
grant_access = grant_note_access(private_file.request, message=self.get_object())
return grant_access
Iam in the testing phase with this library too!
I did not use these lines that indicated, which serves to speed up uploading large files.
without these settings and debug = False, everything worked correctly.
Take the test please.
Sorry for the Translation, I don't speak English
My conf for my site in nginx mysite.conf
server {
listen 80;
server_name mysite.com.br;
return 301 https://mysite.com.br$request_uri;
}
server {
listen 443 ssl http2;
listen [::]:443 ssl http2;
server_name mysite.com.br;
location ~ ^/.well-known{
root /var/www/myapp;
}
location / {
proxy_pass http://127.0.0.1:6010; # My container is at port 3020
}
ssl_session_timeout 1d;
ssl_session_cache shared:MozSSL:10m; # about 40000 sessions
ssl_session_tickets off;
# Certificate free letsencrypt
ssl_certificate /etc/letsencrypt/live/mysite.com.br/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/mysite.com.br/privkey.pem;
ssl_protocols TLSv1.2 TLSv1.3;
add_header Strict-Transport-Security "max-age=63072000" always;
# OCSP stapling
ssl_stapling on;
ssl_stapling_verify on;
}
My setting.py for django:
MEDIA_ROOT = os.path.join(BASE_DIR, 'anexosapp') # Folder for files private app
MEDIA_URL = '/docs/'
# Conf for django-private-storage
INSTALLED_APPS += (
'private_storage',
)
PRIVATE_STORAGE_ROOT = os.path.join(BASE_DIR, 'anexosapp/')
PRIVATE_STORAGE_AUTH_FUNCTION = 'private_storage.permissions.allow_authenticated' # allow user authenticated
# settings for static server over whitenoise
STATIC_URL = '/static/'
STATICFILES_DIRS = [os.path.join(BASE_DIR, "static"), ]
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
STATICFILES_STORAGE = 'whitenoise.storage.CompressedStaticFilesStorage'
urls.py app main:
urlpatterns += [
path('private-media/', include(private_storage.urls)),
]
The file access url looks like this
https : //mysite.com.br/private-media/docs/namefile.pdf
If anyone finds errors, tips for improving the settings, please indicate! Thank you
I just removed from nginx.conf location that refers to private media like so:
upstream "my domain" {
server web:8000;
}
server {
listen 80;
location / {
proxy_pass http://"my domain";
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $host;
proxy_redirect off;
}
location /staticfiles/ {
alias /home/app/web/staticfiles/;
}
location /mediafiles/ {
alias /home/app/web/mediafiles/;
}
#location /privatefiles/ {
# alias /home/app/web/privatefiles/;
#}
# Error & Access logs
error_log /home/app/logs/error.log error;
access_log /home/app/logs/access.log;
client_max_body_size 128m;
}
Don't forget to set DEBUG = False, then it should worked perfectly. Every time I tried to access to private media without login in, it redirected me to login page.
This is my settings.py
...
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "static")
]
STATIC_URL = "/staticfiles/"
STATIC_ROOT = os.path.join(BASE_DIR, "staticfiles")
MEDIA_URL = "/mediafiles/"
MEDIA_ROOT = os.path.join(BASE_DIR, "mediafiles")
PRIVATE_STORAGE_ROOT = os.path.join(BASE_DIR, "privatefiles")
PRIVATE_STORAGE_AUTH_FUNCTION = 'private_storage.permissions.allow_authenticated'
...
and my main urls.py
from django.conf.urls.static import static
from django.conf.urls import url
from django.contrib import admin
from django.urls import path, include
from django.conf import settings
import private_storage.urls <--- this is for private storage
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('core.urls')),
path('rubric/', include('rubric.urls')),
path('warehouse/', include('warehouse.urls')),
path('preoffers/', include('preoffers.urls')),
path('offers/', include('offers.urls')),
url('^privatefiles/', include(private_storage.urls)) <--- this is for private storage
]
if settings.DEBUG:
urlpatterns += static(
settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
urlpatterns += static(
settings.STATIC_URL, document_root=settings.STATIC_ROOT)
'internal' param tells nginx it's not accessible from the outside.
We access application and then redirect to nginx
settings.py
PRIVATE_STORAGE_ROOT = os.path.join(BASE_DIR, 'private-media')
PRIVATE_STORAGE_AUTH_FUNCTION = 'private_storage.permissions.allow_staff'
PRIVATE_STORAGE_SERVER = 'nginx'
PRIVATE_STORAGE_INTERNAL_URL = '/private-x-accel-redirect/'
nginx
location /private-x-accel-redirect/ {
internal;
alias /var/www/private-media/;
}

Django Wagtail return HTTP 500 Internal server error

I'm deploying my Wagtail application to production but could not get it to work. I'm following this tutorial https://www.digitalocean.com/community/tutorials/how-to-set-up-django-with-postgres-nginx-and-gunicorn-on-ubuntu-18-04.
The website is work as expected on my server when using development settings, as soon as I changed to production it won't work.
On production, I'm only able to access the admin and sitemap URL.
production.py
from .base import *
with open('/etc/secret_key.txt') as f:
SECRET_KEY = f.read().strip()
DEBUG = False
try:
from .local import *
except ImportError:
pass
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'name',
'USER': 'user',
'PASSWORD': 'password',
'HOST': 'localhost',
'PORT': '',
}
}
# SECURITY WARNING: define the correct hosts in production!
INTERNAL_IPS = ("127.0.0.1")
ALLOWED_HOSTS = ['*']
nginx
# Redirect unencrypted traffic to the encrypted site
server {
listen 80;
server_name domain www.domain IP;
return 301 https://domain$request_uri;
}
server {
client_max_body_size 20M;
listen 443 default ssl;
server_name domain.com IP;
keepalive_timeout 70;
ssl on;
ssl_certificate /etc/nginx/certs.pem;
ssl_certificate_key /etc/nginx/privkey.pem;
location = /favicon.ico { access_log off; log_not_found off; }
location /static/ {
root /home/user/projectdir;
}
location / {
include proxy_params;
proxy_pass http://unix:/run/gunicorn.sock;
}
}
Gunicorn.service
[Unit]
Description=gunicorn daemon
Requires=gunicorn.socket
After=network.target
[Service]
User=sherpa
Group=www-data
WorkingDirectory=/home/user/projectdir
ExecStart=/home/user/projectenv/bin/gunicorn \
--access-logfile - \
--workers 3 \
--bind unix:/run/gunicorn.sock \
project.wsgi_production:application
[Install]
WantedBy=multi-user.target
urls.py
urlpatterns = [
url(r'^django-admin/', admin.site.urls),
url(r'^admin/', include(wagtailadmin_urls)),
url(r'^documents/', include(wagtaildocs_urls)),
url(r'^search/$', search_views.search, name='search'),
url(r'^sitemap.xml', sitemap),
# For anything not caught by a more specific rule above, hand over to
# Wagtail's page serving mechanism. This should be the last pattern in
# the list:
url(r'', include(wagtail_urls)),
# Alternatively, if you want Wagtail pages to be served from a subpath
# of your site, rather than the site root:
# url(r'^pages/', include(wagtail_urls)),
]
I'm having the same issue. If I set to Debug = True, everything works fine. If I set Debug = False I get the 500 error page, but nothing in the logs to tell me an error has been fired. I am using Apache and not nginx.

Django Empty page alone takes 2 seconds to load

I am doing my django project with nginx on google compute engine.
My view file is,
from django.shortcuts import render_to_response
def home(request):
return render_to_response('html/index.html',RequestContext(request))
and my template file index.html
<html>
<head>
<title> Home </title>
</head>
<body>
Wel come to my new project
</body>
</html>
While calling this page alone takes 2.75 seconds to load completely on my server.
It takes 1.8second for FFTB ( waiting time)
Is there any configuration problem for this latency?
my settings file
"""
Django settings for audiotube project.
For more information on this file, see
https://docs.djangoproject.com/en/1.6/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.6/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
#Base root is for outside of the project structure
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
rsa_private_key = BASE_DIR + "/lib/rsa/id_rsa"
#Package root is for inside the project
PACKAGE_ROOT = os.path.abspath(os.path.dirname(__file__))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.6/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '46=+9k)k25rb(b9&&wy9y_xtn3rx2stl#%+0-5o-$-un9o&4hn'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
TEMPLATE_DEBUG = True
THUMBNAIL_DEBUG = True
ALLOWED_HOSTS = ['localhost','example.com', '*']
# Application definition
INSTALLED_APPS = (
#This is for the site name and inbuild framework
'django.contrib.sites',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'app0',
'app1',
'ckeditor',
'social.apps.django_app.default',
'sorl.thumbnail',
'compressor',
'template_timings_panel',
)
COMPRESS_ENABLED = True
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
# other finders..
'compressor.finders.CompressorFinder',
)
MIDDLEWARE_CLASSES = (
'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',
)
ROOT_URLCONF = 'mysite.urls'
WSGI_APPLICATION = 'mysite.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.6/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'mydb',
'USER': 'root',
'PASSWORD': 'password',
'HOST': 'hostingaddre',
'PORT': '',
}
}
# Internationalization
# https://docs.djangoproject.com/en/1.6/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = None
USE_I18N = True
USE_L10N = True
USE_TZ = True
SITE_ID = 1
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.6/howto/static-files/
STATIC_ROOT = '/home/mysite/staticfiles/'
STATIC_URL = '/static/'
# Additional locations of static files
STATICFILES_DIRS = [
os.path.join(PACKAGE_ROOT, "static"),
]
MEDIA_ROOT = os.path.join(PACKAGE_ROOT, "site_media", "media")
MEDIA_URL = '/media/'
# List of callables that know how to import templates from various sources.
TEMPLATE_DIRS = [
os.path.join("templates"),
]
#Template context processors
TEMPLATE_CONTEXT_PROCESSORS = (
"django.core.context_processors.request",
"django.contrib.auth.context_processors.auth",
"django.core.context_processors.debug",
"django.core.context_processors.i18n",
"django.core.context_processors.media",
"django.core.context_processors.static",
"django.core.context_processors.tz",
"django.contrib.messages.context_processors.messages",
'social.apps.django_app.context_processors.backends',
'social.apps.django_app.context_processors.login_redirect',
)
# This two setting needed for downloading CKEDITOR
CKEDITOR_JQUERY_URL = '//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js'
CKEDITOR_UPLOAD_PATH = "uploads/"
CKEDITOR_IMAGE_BACKEND = "pillow"
CKEDITOR_CONFIGS = {
'default': {
'toolbar': 'UltraFull',
'height': 300,
'toolbar_UltraFull': [
['Font', 'FontSize', 'Format'],
['Bold', 'Italic', 'Underline', 'Strike', 'Subscript', 'Superscript', '-', 'RemoveFormat'],
[
'NumberedList', 'BulletedList', '-',
'Outdent', 'Indent', '-',
'Blockquote', '-',
'JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock'
],
['Link', 'Unlink', 'Anchor'],
['Image', 'Flash', 'Table', 'HorizontalRule', 'PageBreak', 'Smiley', 'SpecialChar'],
['Cut', 'Copy', 'Paste', 'PasteText', 'PasteFromWord', '-', 'Undo', 'Redo'],
['TextColor', 'BGColor'],
['Maximize', 'Source'],
],
'toolbarCanCollapse': False,
},
'awesome_ckeditor': {
'toolbar': 'UltraFull',
'height': 300,
'toolbar_UltraFull': [
['Font', 'FontSize', 'Format'],
['Bold', 'Italic', 'Underline', 'Strike', 'Subscript', 'Superscript', '-', 'RemoveFormat'],
[
'NumberedList', 'BulletedList', '-',
'Outdent', 'Indent', '-',
'Blockquote', '-',
'JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock'
],
['Link', 'Unlink', 'Anchor'],
['Image', 'Flash', 'Table', 'HorizontalRule', 'PageBreak', 'Smiley', 'SpecialChar'],
['Cut', 'Copy', 'Paste', 'PasteText', 'PasteFromWord', '-', 'Undo', 'Redo'],
['TextColor', 'BGColor'],
['Maximize', 'Source'],
],
'toolbarCanCollapse': False,
},
}
AUTHENTICATION_BACKENDS = (
'users.backends.EmailAuthBackend',
'social.backends.facebook.FacebookOAuth2',
'social.backends.google.GoogleOAuth2',
'social.backends.twitter.TwitterOAuth',
'django.contrib.auth.backends.ModelBackend',
)
SOCIAL_AUTH_FACEBOOK_KEY ="XXXXXXXXXXXXX"
SOCIAL_AUTH_FACEBOOK_SECRET ="XXXXXXXXXXXXX"
SOCIAL_AUTH_FACEBOOK_SCOPE = ['email']
SOCIAL_AUTH_GOOGLE_OAUTH2_KEY ="XXXXXXXXXXXXX"
SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = "XXXXXXXXXXXXX"
SOCIAL_AUTH_FORCE_EMAIL_VALIDATION = True
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
SITE_URL="http://example.com:8000/"
'''
#Use this for exception handling
SOCIAL_AUTH_PIPELINE = (
'social.pipeline.social_auth.associate_by_email',
)
'''
SOCIAL_AUTH_PIPELINE = (
'social.pipeline.social_auth.social_details',
'social.pipeline.social_auth.social_uid',
'social.pipeline.social_auth.auth_allowed',
'social.pipeline.social_auth.social_user',
'social.pipeline.user.get_username',
'users.pipeline.require_email',
#'social.pipeline.mail.mail_validation',
'social.pipeline.user.create_user',
'users.pipeline.save_profile',
'social.pipeline.social_auth.associate_user',
'social.pipeline.social_auth.load_extra_data',
'social.pipeline.user.user_details',
#'social.pipeline.debug.debug'
)
# login redirect urls
LOGIN_URL = "/signin"
LOGIN_REDIRECT_URL = "/dashboard"
DOMAIN = "http://example.com:8000"
if DEBUG:
INTERNAL_IPS = ('127.0.0.1',)
MIDDLEWARE_CLASSES += (
'debug_toolbar.middleware.DebugToolbarMiddleware',
)
INSTALLED_APPS += (
'debug_toolbar',
)
DEBUG_TOOLBAR_PANELS = (
'template_timings_panel.panels.TemplateTimings.TemplateTimings',
'debug_toolbar.panels.version.VersionDebugPanel',
'debug_toolbar.panels.timer.TimerDebugPanel',
'debug_toolbar.panels.sql.SQLPanel',
#'debug_toolbar.panels.settings_vars.SettingsVarsDebugPanel',
'debug_toolbar.panels.headers.HeaderDebugPanel',
#'debug_toolbar.panels.profiling.ProfilingDebugPanel',
'debug_toolbar.panels.request_vars.RequestVarsDebugPanel',
'debug_toolbar.panels.sql.SQLDebugPanel',
'debug_toolbar.panels.template.TemplateDebugPanel',
'debug_toolbar.panels.cache.CacheDebugPanel',
'debug_toolbar.panels.signals.SignalDebugPanel',
#'debug_toolbar.panels.logger.LoggingPanel',
)
DEBUG_TOOLBAR_CONFIG = {
'INTERCEPT_REDIRECTS': False,
}
PREPEND_WWW = True
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.filebased.FileBasedCache',
'LOCATION': '/var/tmp/django_cache',
}
}
TEMPLATE_LOADERS = (
('django.template.loaders.cached.Loader', (
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
)),
)
In example.com which is inside /etc/nginx/site-enabled and site-available
server {
listen 80;
server_name myservername.com;
client_max_body_size 4G;
error_page 502 =200 #maintenance;
location #maintenance {
root /path/to/static/offline/files;
try_files $uri /index.html =503;
}
location /static/ {
alias /home/sim/5vs/staticfiles/;
}
location /media/ {
alias /home/sim/5vs/myproject/myproject/site_media/media/;
expires 30d;
}
location / {
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $http_host;
proxy_redirect off;
}
}
in nginx.conf file has
user root;
worker_processes 4;
pid /run/nginx.pid;
events {
worker_connections 768;
# multi_accept on;
}
http {
sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 65;
types_hash_max_size 2048;
include /etc/nginx/mime.types;
default_type application/octet-stream;
access_log /var/log/nginx/access.log;
error_log /var/log/nginx/error.log;
gzip on;
gzip_disable "msie6";
include /etc/nginx/conf.d/*.conf;
include /etc/nginx/sites-enabled/*;
}
Could you please tell why it takes long time and what's wrong in my configuration.
On using Profiler
Total time: 1.89419 s
File: /home/staging/live/users/views.py
Function: comingsoon_view at line 93
Line # Hits Time Per Hit % Time Line Contents
93 def comingsoon_view(request):
94 1 2 2.0 0.0 temp = {}
95 1 1894189 1894189.0 100.0 return render(request, 'pages/comingsoon.html',temp)
User using debug server with DEBUG=True setting to run django project. It enables DEBUG toolbar - which is really slow. It's normal time with this settings. If you'll disable this - I think everything will be fine.
If you will still have troubles - I recommend you to check django debug server response time(python manage.py runserver). If it faster then problem is nginx configuration or, if the same - you should check timings with lineprofiler.
If it's production configuration - don't use debug server on production. You should use gunicorn or something similar to run django projects.

How to setup production ubuntu server with django, gunicorn, nginx and celery?

I need to setup production server on ubuntu precise, I read lot of howtos and put bits and pieces together.Below I will post (hopefully) all related configs. But to point you where to look first I list all the problems:
when I don't manually type https:// I got incorrect redirect in firefox
when I type https:// I got to admin login but can't login with correct username/pass and I don't know how to debug it because I can't find any log containing what runserver outputs to console(i tried file logger in settings.py but log stays empty)
my app runs under subdomain.domain.com -should I put subdomain.domain.com or just domain.com in settings.py DOMAIN= ?
what to chenge to make gunicorn work with self signed certificate as in commented line ingunicorn.conf?
Why /var/log/upstart/celercam.log is full of Error in timer: TransactionManagementError("This code isn't under transaction management",)
pip freeze:
Django==1.5.4
MySQL-python==1.2.4
PIL==1.1.7
Pillow==2.2.1
PyYAML==3.10
South==0.8.4
amqp==1.3.3
anyjson==0.3.3
argparse==1.2.1
billiard==3.3.0.8
celery==3.1.5
django-celery==3.1.1
django-crispy-forms==1.4.0
django-money==0.3.3
django-sortable-listview==0.23
easy-thumbnails==1.4
gevent==1.0
google-api-python-client==1.2
greenlet==0.4.1
gunicorn==18.0
httplib2==0.8
kombu==3.0.6
oauth2client==1.2
psycopg2==2.5.1
py==1.4.17
py-moneyed==0.4.1
pyadb==0.1.1
pyaml==13.07.1
pylibmc==1.2.3
pytest==2.4.2
python-dateutil==2.1
python-gflags==2.0
pytz==2013.8
reportlab==2.7
six==1.4.1
vobject==0.8.1c
wsgiref==:
0.1.2
settings.py
# Django settings for crm project.
DEBUG = False
TEMPLATE_DEBUG = DEBUG
ADMINS = (
# ('Your Name', 'your_email#example.com'),
)
DOMAIN = '<MY_DOMAIN>'
MANAGERS = ADMINS
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': '<DB_NAME>', # Or path to database file if using sqlite3.
'USER': '<DB_USER>',
'PASSWORD': '<DB_PASS>',
'HOST': '127.0.0.1',
'PORT': '',
}
}
ALLOWED_HOSTS = ['*',]
TIME_ZONE = 'Europe/Warsaw'
LANGUAGE_CODE = 'pl'
SITE_ID = 1
USE_I18N = True
USE_L10N = True
USE_TZ = True
MEDIA_ROOT = '/var/www/media/'
MEDIA_URL = '/media/'
STATIC_ROOT ='/var/www/static/'
STATIC_URL = '/static/'
# Additional locations of static files
STATICFILES_DIRS = (
)
# List of finder classes that know how to find static files in
# various locations.
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
# 'django.contrib.staticfiles.finders.DefaultStorageFinder',
)
# Make this unique, and don't share it with anybody.
SECRET_KEY = '<NOT_THAT_STUPID>'
# List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
# 'django.template.loaders.eggs.Loader',
)
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
# Uncomment the next line for simple clickjacking protection:
# 'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
ROOT_URLCONF = 'crm.urls'
# Python dotted path to the WSGI application used by Django's runserver.
WSGI_APPLICATION = 'crm.wsgi.application'
import os
SESSION_COOKIE_SECURE = True
TEMPLATE_DIRS = (os.path.join(os.path.dirname(__file__), '..', 'templates').replace('\\', '/'),)
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.humanize',
'django.contrib.admin',
'main',
'crm',
'crispy_forms',
'django_localflavor_us',
'django_localflavor_pl',
'investApp',
'addressbook',
'sortable_listview',
'djcelery',
'gunicorn',
# 'south'
)
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'formatters': {
'verbose': {
'format': "[%(asctime)s] %(levelname)s [%(name)s:%(lineno)s] %(message)s",
'datefmt': "%d/%b/%Y %H:%M:%S"
},
'simple': {
'format': '%(levelname)s %(message)s'
},
},
'filters': {
'require_debug_false': {
'()': 'django.utils.log.RequireDebugFalse'
}
},
'handlers': {
'mail_admins': {
'level': 'ERROR',
'filters': ['require_debug_false'],
'class': 'django.utils.log.AdminEmailHandler'
},
'console': {
'level': 'DEBUG',
'class': 'logging.StreamHandler',
'formatter': 'simple',
},
'file': {
'level': 'INFO',
'class': 'logging.FileHandler',
'filename': '/home/<USER>/spcrm/debug.log',
},
},
'loggers': {
'django.request': {
'handlers': ['mail_admins'],
'level': 'ERROR',
'propagate': True,
},
'investApp': {
'handlers': ['console'],
'level': 'DEBUG',
}
}
}
#memcache
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.memcached.PyLibMCCache',
'LOCATION': '127.0.0.1:11211',
}
}
#djcelery
BROKER_URL = "amqp://<USER>:<PASS>#localhost:5672/crm"
CELERY_RESULT_BACKEND = "database"
CELERY_RESULT_DBURI = "postgresql://<USER>:<PASS>#localhost/spcrm"
#crispy_forms theme
CRISPY_TEMPLATE_PACK = 'bootstrap'
DEFAULT_CHARSET = 'utf-8'
DEFAULT_CURRENCY = 'PLN'
LOGIN_URL = 'LogMeIn'
LOGIN_REDIRECT_URL = 'after_login'
# Converting warnings to errs to get line no NOT IN PRODUCTION!
# warnings.filterwarnings(
# 'error', r"DateTimeField received a naive datetime",
# RuntimeWarning, r'django\.db\.models\.fields')
# put these two lines at the very bottom of the settings file
import djcelery
djcelery.setup_loader()
/etc/init/celeryd.conf:
description "celeryd"
start on (filesystem)
stop on runlevel [016]
respawn
console log
setuid <USER>
setgid nogroup
chdir /home/<USER>/spcrm
exec /home/<USER>/.virtualenvs/crm/bin/python /home/<USER>/spcrm/manage.py celeryd -B -E -loglevel=DEBUG
/etc/init/gunicorn.conf:
description "gunicorn"
start on (filesystem)
stop on runlevel [016]
respawn
console log
setuid <USER>
setgid nogroup
chdir /home/<USER>/spcrm
#exec /home/<USER>/.virtualenvs/crm/bin/python /home/<USER>/spcrm/manage.py run_gunicorn -w 3 -k gevent --certfile=/home/<USER>/guni-cert.pem --keyfile=/home/<USER>uni-key.pem
exec /home/<USER>/.virtualenvs/crm/bin/python /home/<USER>/spcrm/manage.py run_gunicorn
/etc/nginx/sites-enabled/spcrm:
server {
listen 80;
# If you want certain Non-SSL areas on your site, add a location block here
# read up on the nginx docs.
# Be sure to replace localhost in the following rule to the server name/IP address.
return 301 https://subdomain.domain.com/;
}
server {
listen 443 ssl;
# server_name _;
# start mine
ssl on;
ssl_certificate /home/<USER>/guni-cert.pem;
ssl_certificate_key /home/<USER>/guni-key.pem;
ssl_protocols SSLv3 TLSv1 TLSv1.1 TLSv1.2;
ssl_ciphers HIGH:!aNULL:!MD5;
server_name localhost;
root /home/<USER>/spcrm/crm;
access_log /var/log/nginx/spcrm.access.log;
error_log /var/log/nginx/spcrm.error.log;
location /static/{
autoindex on;
root /var/www/;
}
location / {
proxy_pass_header Server;
proxy_set_header Host $http_host;
proxy_redirect off;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Scheme $scheme;
proxy_connect_timeout 10;
proxy_read_timeout 10;
proxy_pass http://localhost:8000/;
}
error_page 404 /404.html;
location = /404.html {
root /usr/share/nginx/html;
}
# redirect server error pages to the static page /50x.html
#
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root /usr/share/nginx/html;
}
}