Skip to content

Commit

Permalink
feat: support X-Forwarded-* headers
Browse files Browse the repository at this point in the history
Makes it easy to serve the application behind a reverse proxy.
When the environment variable `BEHIND_PROXY` is set to a truthy
value (1, t, true, y, yes), the `ProxyFix` middleware is used to
trust and honour the X-Forwarded-* headers (up to one level).
  • Loading branch information
derlin committed Apr 12, 2023
1 parent c5caa96 commit 73ad575
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 0 deletions.
4 changes: 4 additions & 0 deletions docs/quickstart.md
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,10 @@ The application can be tuned using environment variables.
**Security**

* `APP_SECRET_KEY`: The Flask Secret Key used for CSRF tokens and sessions. Default to `urandom(10)`.
* `BEHIND_PROXY`: If set to a truthy value (one of `1`, `t`, `true`, `yes`, `y` case-insensitive),
the app will trust and honour the `X-Forwarded-*` headers (up to one level). Only use it when the app runs behind
a reverse proxy. See [ProxyFix](https://werkzeug.palletsprojects.com/en/latest/middleware/proxy_fix/)
for more information.

**Persistence**

Expand Down
5 changes: 5 additions & 0 deletions rickroll/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
from flask_wtf.csrf import CSRFError
from validators.url import url as urlvalidate
from werkzeug.exceptions import NotFound
from werkzeug.middleware.proxy_fix import ProxyFix

from .db import PersistenceError, init_persistence
from .rickroller import RickRoller, RickRollError
Expand All @@ -23,11 +24,15 @@ def create_app():
env_slug_retention_unit = getenv("SLUG_RETENTION_UNITS", "minutes")
env_max_urls_per_user = int(getenv("MAX_URLS_PER_USER", 40))
env_scroll_redirects_after_default = int(getenv("SCROLL_REDIRECT_AFTER_DEFAULT", 2))
env_behind_proxy = getenv("BEHIND_PROXY", "false").lower() in ["t", "1", "true", "yes", "y"]
# ==

app = Flask(__name__, static_folder="assets")
app.secret_key = env_secret_key

if env_behind_proxy:
app.wsgi_app = ProxyFix(app.wsgi_app, x_prefix=1, x_for=1, x_port=1)

if server_name := getenv("SERVER_NAME"):
app.config["SERVER_NAME"] = server_name
app.logger.info(f"Using server name {server_name}")
Expand Down

0 comments on commit 73ad575

Please sign in to comment.