Skip to content

Commit

Permalink
refine nginx config
Browse files Browse the repository at this point in the history
  • Loading branch information
fabienheureux committed Jan 28, 2025
1 parent 0b4b61b commit e9b3bbc
Show file tree
Hide file tree
Showing 6 changed files with 59 additions and 31 deletions.
4 changes: 2 additions & 2 deletions .secrets.baseline
Original file line number Diff line number Diff line change
Expand Up @@ -160,7 +160,7 @@
"filename": "docker-compose.yml",
"hashed_secret": "3cf2012487b086bba2adb3386d69c2ab67a268b6",
"is_verified": false,
"line_number": 49
"line_number": 50
}
],
"iframe_without_js.html": [
Expand Down Expand Up @@ -207,5 +207,5 @@
}
]
},
"generated_at": "2025-01-28T09:33:27Z"
"generated_at": "2025-01-28T10:16:27Z"
}
2 changes: 1 addition & 1 deletion core/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@
"corsheaders.middleware.CorsMiddleware",
"django.middleware.security.SecurityMiddleware",
"whitenoise.middleware.WhiteNoiseMiddleware",
"qfdmd.middleware.RemoveCookieFromVaryMiddleware",
"qfdmd.middleware.AssistantMiddleware",
"django.middleware.common.CommonMiddleware",
"django.middleware.csrf.CsrfViewMiddleware",
"django.contrib.sessions.middleware.SessionMiddleware",
Expand Down
1 change: 1 addition & 0 deletions docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ services:
volumes:
- ./nginx/servers.conf:/etc/nginx/servers.conf
- ./nginx/nginx.conf:/etc/nginx/nginx.conf
- ./staticfiles:/app/staticfiles
profiles: [proxy]
ports:
- "8080:80"
Expand Down
19 changes: 9 additions & 10 deletions nginx/servers.conf
Original file line number Diff line number Diff line change
@@ -1,16 +1,20 @@
proxy_cache_path /tmp/nginx_assistant_cache levels=1:2 keys_zone=assistant:10m max_size=1g inactive=60m use_temp_path=off;
# Define a variable to disable cache if the logged_in cookie is set
map $http_cookie $no_cache {
default 0;
"~*logged_in=.*" 1;
}

server {
listen 80;
server_name _;

location /static/ {
expires max;
alias /app/staticfiles/;
}

location / {
proxy_pass http://host.docker.internal:8000;

proxy_cache_bypass $no_cache;
proxy_no_cache $no_cache;

proxy_cache assistant;
proxy_set_header Host $http_host;
proxy_cache_key $request_method$request_uri$is_args$args;
Expand All @@ -20,9 +24,4 @@ server {
proxy_cache_background_update on;
add_header X-Cache-Status $upstream_cache_status;
}

location ~ ^/(favicon(?:-\d+)?.(?:jpe?g|png|ico))$ {
access_log off;
log_not_found off;
}
}
53 changes: 35 additions & 18 deletions qfdmd/middleware.py
Original file line number Diff line number Diff line change
@@ -1,27 +1,44 @@
import logging

logger = logging.getLogger(__name__)


class RemoveCookieFromVaryMiddleware:
class AssistantMiddleware:
def __init__(self, get_response):
self.get_response = get_response

def __call__(self, request):
response = self.get_response(request)

self._set_logged_in_cookie(request, response)
self._handle_iframe_cookie(request, response)
self._cleanup_vary_header(response)

return response

def _set_logged_in_cookie(self, request, response):
"""Set or update the 'logged-in' header based on authentication."""
cookie_name = "logged_in"
if request.user.is_authenticated:
response.headers["logged-in"] = 1
else:
del response.headers["Vary"]
response.headers["Vary"] = "iframe, logged-in"
response.set_cookie(cookie_name, "1")
elif request.COOKIES.get(cookie_name):
response.delete_cookie(cookie_name)

if "iframe" in request.GET:
response.set_cookie("iframe", 1)
def _handle_iframe_cookie(self, request, response):
"""Manage iframe-related headers and cookies."""
iframe_in_request = "iframe" in request.GET
iframe_cookie = response.cookies.get("iframe")

if (
response.cookies.get("iframe") == "1"
or request.COOKIES.get("iframe") == "1"
):
response.headers["iframe"] = 1
if iframe_in_request:
response.set_cookie("iframe", "1")
response.headers["iframe"] = "1"
elif iframe_cookie and iframe_cookie.value == "1":
response.headers["iframe"] = "1"
else:
# Ensure the iframe header is not lingering
response.headers.pop("iframe", None)

return response
@staticmethod
def _cleanup_vary_header(response):
"""Helper to parse and return the Vary header as a list."""
vary_header = response.headers.get("Vary", "")
return [
v.strip()
for v in vary_header.split(",")
if v.strip() and v.strip().lower() != "cookie"
]
11 changes: 11 additions & 0 deletions servers.conf.erb
Original file line number Diff line number Diff line change
@@ -1,5 +1,12 @@
proxy_cache_path /tmp/nginx_assistant_cache levels=1:2 keys_zone=assistant:10m max_size=1g inactive=60m use_temp_path=off;

# Define a variable to disable cache if the specific cookie is set
map $http_cookie $no_cache {
default 0; # Enable caching by default
"~*logged_in=.*" 1; # Disable caching if 'logged_in' is set
}


server {
listen <%= ENV["PORT"] %>;
server_name _;
Expand All @@ -12,6 +19,10 @@ server {

location / {
proxy_pass http://unix:/tmp/gunicorn.sock;

proxy_cache_bypass $no_cache;
proxy_no_cache $no_cache;

proxy_cache assistant;
proxy_set_header Host $http_host;
proxy_cache_key $request_method$request_uri$is_args$args;
Expand Down

0 comments on commit e9b3bbc

Please sign in to comment.