Restrict access to your Discourse site with HTTP Basic Authentication

Sometimes you don’t want the general public to be able to access your Discourse instance quite yet, like when you’re staging a site for a migration.

NOTE: I have had some trouble with basic-auth recently in which some static assets weren’t getting loaded. It might be easier to just configure your site for login_required by adding DISCOURSE_LOGIN_REQUIRED: true in the env section of your app.yml.

The following setup will put up a simple browser confirm dialog asking for username and password, common to all visitors, that will be required before they can access the site.

:information_source: Note: Users will still need to perform normal Discourse registration and login.

basic auth credentials

Generate encrypted password

htpasswd -bn =username= =password=

Note: You’ll need htpasswd for this. In Ubuntu/Debian, it is in apache2-utils. If you have access to some other machine with htpasswd installed, you can just run it there. If your goal is merely to keep out search engines, there is no reason not to use the example password here.

encrypted user/password goes here

Add to app.yml

# basic auth
  after_bundle_exec:
    - replace:
       filename: "/etc/nginx/conf.d/discourse.conf"
       from: "# auth_basic on"
       to: "auth_basic on"
    - replace:
       filename: "/etc/nginx/conf.d/discourse.conf"
       from: "# auth_basic_user_file /etc/nginx/htpasswd"
       to: "auth_basic_user_file /etc/nginx/htpasswd"
    - replace:
       filename: "/etc/nginx/conf.d/discourse.conf"
       from: "location = /srv/status {"
       to: "location = /srv/status {
           auth_basic off;"
    - file:
       path: "/etc/nginx/htpasswd"
       contents: |
         =auth_string=    

The after_bundle_exec section changes the configuration of the nginx inside the discourse container. When you’re ready to go live, just delete this section and rebuild.

13 Likes