How to Set Up Authelia SSO and 2FA Behind an Nginx Reverse Proxy

One monitoring dashboard asks for a login. A file panel asks for another. An RSS reader has a third form. Each service guards its own door with its own password, and every additional door is another one to watch. Authelia turns that layout inside out: a single login gate in front of everything, enforced by Nginx, with a one-time code as the second layer. The apps behind the gate stay untouched, because Nginx asks Authelia before forwarding any request at all.

The flow is short. A visitor opens files.example.com. Nginx sends a subrequest to Authelia. A 200 answer means the request goes through to the app, carrying a Remote-User header. A 401 answer sends the visitor to the login portal at auth.example.com. Once the password checks out and the TOTP code matches, a session cookie lets later visits through until it expires.

Before touching any configuration

This guide assumes one VPS with Docker and Docker Compose, one parent domain (example.com), and DNS already pointing at the VPS for auth.example.com plus every subdomain you plan to protect. TLS is assumed to be handled in the Nginx server blocks; the examples use listen 443 ssl and an ssl.conf snippet as the place where your certificates live. Replace example.com with your own domain everywhere, no exceptions.

One prerequisite gets skipped often: Nginx must be built with the http_auth_request and http_realip modules. Authelia's Nginx integration guide lists both as requirements. Check with:

nginx -V 2>&1 | grep -- 'http_auth_request_module'
nginx -V 2>&1 | grep -- 'http_realip_module'

No output means you need a different Nginx package or image that includes those modules. Without them, the auth_request directive is unknown and Nginx refuses to load.

Step 1: Lay out the Docker Compose stack

Create a project directory with three services — Authelia, Redis, and Nginx — on one shared Docker network. That shared network matters, because Nginx reaches Authelia by container name, not by host IP.

mkdir -p ~/authelia-stack/authelia ~/authelia-stack/nginx/snippets
cd ~/authelia-stack

Fill in docker-compose.yml:

services:
  authelia:
    image: authelia/authelia
    container_name: authelia
    restart: unless-stopped
    networks:
      - net
    volumes:
      - ./authelia:/config
    environment:
      - TZ=Asia/Jakarta
  redis:
    image: redis:alpine
    container_name: redis
    restart: unless-stopped
    networks:
      - net
    volumes:
      - ./authelia/redis:/data
    command: redis-server --appendonly yes
  nginx:
    image: nginx:alpine
    container_name: nginx
    restart: unless-stopped
    networks:
      - net
    ports:
      - "80:80"
      - "443:443"
    volumes:
      - ./nginx/snippets:/etc/nginx/snippets
      - ./nginx/conf.d:/etc/nginx/conf.d
networks:
  net:
    driver: bridge

Notice a deliberate choice here: Authelia's port (9091) is not published to the host. Only Nginx needs to reach it, by the name authelia on the net network. Keeping that port off the internet shrinks the attack surface without changing any behavior, since the login portal is still reached through auth.example.com, proxied by Nginx.

Redis holds the sessions. Without it, Authelia keeps sessions in memory, and every container restart logs everyone out. With Redis, sessions survive an Authelia restart, as long as the Redis data itself is not wiped.

Step 2: Write configuration.yml

Authelia's main file lives at ~/authelia-stack/authelia/configuration.yml. Generate three random strings for the secrets — one command, run three times, gives a 64-character hex string each time:

openssl rand -hex 32

Use one output for the session secret, one for the storage encryption key, and one for the JWT secret. Paste them into the file, then lock the file down to owner-only reads:

chmod 600 ~/authelia-stack/authelia/configuration.yml

The configuration.yml contents:

server:
  address: 'tcp4://:9091'
  endpoints:
    authz:
      auth-request:
        implementation: 'AuthRequest'
log:
  level: 'info'
  keep_stdout: true
totp:
  disable: false
  issuer: 'example.com'
  period: 30
  skew: 1
identity_validation:
  reset_password:
    jwt_lifespan: '5 minutes'
    jwt_secret: 'PASTE-YOUR-RANDOM-JWT-SECRET'
authentication_backend:
  file:
    path: '/config/users.yml'
    password:
      algorithm: 'argon2'
      argon2:
        variant: 'argon2id'
        iterations: 3
        memory: 65535
        parallelism: 4
        key_length: 32
        salt_length: 16
access_control:
  default_policy: 'deny'
  rules:
    - domain: 'monitor.example.com'
      policy: 'one_factor'
      subject:
        - 'group:team'
    - domain: 'files.example.com'
      policy: 'two_factor'
    - domain: '*.example.com'
      policy: 'two_factor'
session:
  name: 'authelia_session'
  secret: 'PASTE-YOUR-RANDOM-SESSION-SECRET'
  cookies:
    - domain: 'example.com'
      authelia_url: 'https://auth.example.com'
      default_redirection_url: 'https://www.example.com'
  redis:
    host: 'redis'
    port: 6379
regulation:
  max_retries: 4
  find_time: 120
  ban_time: 300
storage:
  encryption_key: 'PASTE-YOUR-RANDOM-STORAGE-ENCRYPTION-KEY'
  local:
    path: '/config/db.sqlite3'
notifier:
  disable_startup_check: false
  filesystem:
    filename: '/config/notification.txt'

A few sections deserve a closer look, because a typo here produces confusing symptoms later.

The server.endpoints.authz block tells Authelia to serve authorization with the AuthRequest implementation, the official counterpart to Nginx's auth_request directive. Without it, the endpoint Nginx calls does not behave as expected.

The session.cookies section is the heart of cross-subdomain SSO. domain: 'example.com' makes the session cookie valid for auth.example.com, files.example.com, and every other subdomain beneath it. That is why one login opens many services. authelia_url must match the portal address visitors actually see, including https://. An http:// value behind TLS is one of the classic causes of the redirect loop covered at the end of this guide.

The session.redis block points at the container named redis on port 6379. That hostname has to match the service name in Compose exactly. A single wrong letter breaks session storage.

The notifier.filesystem setting is a conscious choice for the first run: password-reset links are written to /config/notification.txt instead of emailed. That makes the initial setup easy, but it is no good for users without server access. Once everything works, switch to SMTP so reset links reach real inboxes.

The regulation block throttles password guessing: four failed attempts inside the window trigger a temporary ban. This is not decoration; a login page exposed to the internet will get probed sooner or later.

Step 3: Create the user database

Authelia never stores raw passwords. Each password is turned into an Argon2id hash, and the hash is what goes into users.yml. Generate a hash for the first user with Authelia's own image, no extra tooling needed:

docker run --rm authelia/authelia authelia crypto hash generate argon2 --password 'Your-Strong-Password'

The output is one long line starting with $argon2id$. Copy the whole line into ~/authelia-stack/authelia/users.yml:

users:
  andi:
    displayname: 'Andi Pratama'
    password: 'PASTE-FULL-ARGON2ID-HASH'
    email: 'andi@example.com'
    groups:
      - 'team'
      - 'admins'
  sari:
    displayname: 'Sari Wulandari'
    password: 'PASTE-FULL-ARGON2ID-HASH'
    email: 'sari@example.com'
    groups:
      - 'team'

Groups here are not cosmetic labels. The access rule in the previous step uses group:team to decide who may enter monitor.example.com. A user outside that group is refused even with the right password.

Before starting anything, one note on validation: Authelia parses configuration.yml at startup. The check that matches the official documentation is to start the stack and read the startup log; a bad file stops the container from starting and the log names the cause. Step 4 below uses that method, so do not skip reading the log.

Step 4: Start the stack and read the logs

cd ~/authelia-stack
docker compose up -d
docker compose ps
docker compose logs -f authelia

Expect all three containers running, and no fresh errors in the Authelia log after the initial startup lines. If the Authelia container restarts in a loop, do not guess; read the last error line in the log, which almost always names the configuration key at fault. Once things look stable, stop the log tail with Ctrl+C (the containers keep running in the background).

Step 5: Wire Nginx up with auth_request

Nginx needs two snippets. The first, ~/authelia-stack/nginx/snippets/authelia-location.conf, defines the internal endpoint used by the subrequest. It follows Authelia's official Nginx integration example:

set $upstream_authelia http://authelia:9091/api/authz/auth-request;

location /internal/authelia/authz {
    internal;
    proxy_pass $upstream_authelia;

    proxy_set_header X-Original-Method $request_method;
    proxy_set_header X-Original-URL $scheme://$host$request_uri;
    proxy_set_header X-Forwarded-For $remote_addr;
    proxy_set_header Content-Length "";
    proxy_set_header Connection "";

    proxy_pass_request_body off;
    proxy_next_upstream error timeout invalid_header http_500 http_502 http_503;
    proxy_redirect http:// $scheme://;
    proxy_http_version 1.1;
    proxy_cache_bypass $cookie_session;
    proxy_no_cache $cookie_session;
    proxy_buffers 4 32k;
    client_body_buffer_size 128k;

    send_timeout 5m;
    proxy_read_timeout 240;
    proxy_send_timeout 240;
    proxy_connect_timeout 240;
}

The word internal means this location cannot be opened directly from a browser. Only Nginx itself may call it as a subrequest. The X-Original-URL header tells Authelia which URL was really requested, so after login the user lands back on that page rather than the portal homepage.

The second snippet, ~/authelia-stack/nginx/snippets/authelia-authrequest.conf, goes inside every location you want protected:

auth_request /internal/authelia/authz;

auth_request_set $user $upstream_http_remote_user;
auth_request_set $groups $upstream_http_remote_groups;
auth_request_set $name $upstream_http_remote_name;
auth_request_set $email $upstream_http_remote_email;

proxy_set_header Remote-User $user;
proxy_set_header Remote-Groups $groups;
proxy_set_header Remote-Email $email;
proxy_set_header Remote-Name $name;

auth_request_set $redirection_url $upstream_http_location;
error_page 401 =302 $redirection_url;

The mechanics follow Nginx's subrequest rule: a 2xx answer allows access, 401 or 403 denies it. The auth_request_set lines copy Authelia's answer headers into Nginx variables, which are then forwarded to the app as Remote-User and friends. Apps that support header authentication can recognize the user straight from those values. One important warning: those headers are only trustworthy if the app is reachable solely through Nginx. If the app is also exposed directly, anyone could forge Remote-User by sending the header themselves.

Now the server blocks. The Authelia portal does not use the authrequest snippet, because the portal is where login happens. Put this in ~/authelia-stack/nginx/conf.d/auth.conf:

server {
    listen 443 ssl;
    server_name auth.example.com;
    include /etc/nginx/snippets/ssl.conf;

    location / {
        proxy_pass http://authelia:9091;
        proxy_set_header Host $host;
        proxy_set_header X-Original-URL $scheme://$host$request_uri;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_set_header X-Forwarded-Host $host;
        proxy_set_header X-Forwarded-URI $request_uri;
        proxy_set_header X-Forwarded-For $remote_addr;
        proxy_set_header X-Real-IP $remote_addr;
    }
}

A protected service block, say files.conf, looks like this:

server {
    listen 443 ssl;
    server_name files.example.com;
    include /etc/nginx/snippets/ssl.conf;
    include /etc/nginx/snippets/authelia-location.conf;

    location / {
        include /etc/nginx/snippets/authelia-authrequest.conf;
        proxy_pass http://files-app:8080;
        proxy_set_header Host $host;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_set_header X-Forwarded-For $remote_addr;
    }
}

Replace files-app:8080 with your app's address. The same pattern covers each new service: one server block, one location include at server level, one authrequest include inside location. A service without the authrequest include is not protected, no matter what configuration.yml says.

Test and reload Nginx:

docker compose exec nginx nginx -t
docker compose exec nginx nginx -s reload

Expect syntax is ok and test is successful from nginx -t. If it fails, the error names the file and line number; fix it there instead of guessing.

Step 6: Turn on TOTP for users

Open https://auth.example.com and sign in with a user from users.yml. On the first sign-in for a two_factor service, the portal asks you to register a second factor. Open an authenticator app on your phone, scan the QR code shown, then enter the six-digit code it displays. Codes rotate every 30 seconds, matching period: 30 in the configuration, and Authelia tolerates one step of clock drift either way through skew: 1.

Test in a way you can see. Open https://files.example.com in a private window: Nginx should send you to the portal. Signing in with the password alone is not enough; the portal asks for the TOTP code. After the correct code, the browser returns to files.example.com and the page loads. Open https://monitor.example.com in the same tab: no second login, because the session cookie is still valid. That is SSO doing its job.

If codes keep getting rejected while the password works, check the server clock first:

timedatectl status

TOTP depends on synchronized clocks. A drift beyond one 30-second step is enough for the phone's code and the server's calculation to miss each other. Turn on automatic time sync and try again before changing anything else.

Choosing between one_factor and two_factor

Rules are evaluated top to bottom, and the first match wins. Order is therefore behavior, not tidiness. A broad rule placed on top swallows the specific rules below it.

SubdomainRuleWhat the user experiences
monitor.example.comone_factor, group teamPassword is enough, but only for members of group team
files.example.comtwo_factorPassword plus a TOTP code for every user
*.example.comtwo_factorA safety net for subdomains without their own rule
No matching ruledefault_policy: denyAccess denied, not silently allowed

A sensible pattern: read-only internal dashboards can live with one_factor when their network exposure is already limited, while anything that changes or downloads data gets two_factor. Avoid bypass except for assets genuinely meant to be public, and never pair bypass with a subject restriction, since that combination is rejected: Authelia cannot know who the subject is without at least one authentication factor.

Redirect loops: a diagnosis in order

The most common post-install symptom is a browser spinning between the app and the portal, never showing a page. Work through these checks in order, from the most frequent cause to the rarer ones.

First, check the cookie domain. session.cookies.domain must be example.com, not auth.example.com. A cookie written for auth.example.com is invisible when the user returns to files.example.com, so Nginx treats them as logged out, sends them to the portal, the portal sees its own cookie still there, sends them back, and the loop repeats.

Second, check authelia_url. It must be exactly https://auth.example.com, the same address visitors open. An http scheme behind TLS, or a hostname off by one letter, is enough to break the redirect.

Third, check the forwarding headers in the portal block. If X-Forwarded-Proto is not passed along, Authelia may think the request arrived over HTTP and keep redirecting to HTTPS while Nginx does the reverse. Make sure the portal block forwards X-Forwarded-Proto $scheme.

Fourth, clear stale cookies in the browser. A leftover authelia_session cookie from an earlier configuration attempt may hold a session signed with an old secret. Changing the session secret invalidates all old sessions; users have to sign in again, and an uncleaned stale cookie sometimes makes the portal behave oddly.

Fifth, read both sides' logs at once. In one terminal, run docker compose logs -f authelia. In another, check the Nginx error log. An auth_request returning 500 usually means Nginx cannot reach Authelia: wrong container name, different network, or Authelia mid-restart. A repeated 401 with no other error points at access rules or cookies, not connectivity.

Final checklist

  • nginx -V shows the http_auth_request and http_realip modules
  • docker compose config shows port 9091 not exposed to the host
  • The Authelia container does not restart in a loop and its startup log is clean after docker compose up -d
  • configuration.yml is mode 600 and holds random secrets, not example values
  • The cookie domain is the parent domain, and authelia_url uses https://
  • files.example.com asks for login plus TOTP, monitor.example.com follows its own rule
  • Moving between subdomains after login does not ask for another login
  • The filesystem notifier is replaced with SMTP before other users get accounts
  • Backups of configuration.yml and users.yml live off the server

A single login gate does not automatically make the services behind it safe, but it turns a dozen scattered login forms into one place that can be audited, tightened, and backed up. Start with two services, watch the logs for a week, then add the rest one at a time.

Which service will you protect first with Authelia, and does it need one_factor or two_factor? Leave your answer in the comments, along with any snag you hit while following the steps above.

Read also: How to Install AdGuard Home on a VPS for Private DNS Filtering for a DNS service that can sit behind the same gate, and How to Get a Let's Encrypt Wildcard Certificate via the Cloudflare DNS Challenge for wildcard certificates that simplify TLS for every subdomain.

Diskusi

Ada pertanyaan atau pengalaman yang ingin dibagikan?

0komentar

Komentar ditinjau sebelum ditampilkan. Mari berdiskusi dengan sopan dan sesuai topik.