URL rewrite for domain change in permalinks

Update your hostname for the forum:

DISCOURSE_HOSTNAME: 'www.new-name.com'

Add this to the run: section of your ./containers/app.yml for new domain rewrite url magic the NGINX way:

run:
  ## fix default discourse.conf
  - replace:
      filename: "/etc/nginx/conf.d/discourse.conf"
      from: "listen 80;"
      to: "listen 80 default_server;"
  ## Rewrite www.old-name.com to www.new-name.com
  - replace:
      filename: "/etc/nginx/conf.d/discourse.conf"
      from: "server {"
      to: |
        server {
            listen 80;
            listen 443 ssl;
            server_name www.old-name.com;
            return 301 $scheme://www.new-name.com$request_uri;
        }
        server {

PS. the YAML syntax is very particular about spacing, so make sure you have the indents just right :wink:

https://www.nginx.com/blog/creating-nginx-rewrite-rules/

Lastly, you may need to rebake your posts if they contain references to the old domain; these links will likely go to a dud tracking link as they now appear as external rather than “internal” links. This is fixed by:

cd /var/discourse
./launcher enter app
rake posts:rebake_match["www.old-name.com"]

More info on rebaking options here:

Separate note for Discourse maintainers…
Not sure how important this is overall @codinghorror but it looks like I can’t get a second server { } block to work properly without changing Discourse’s default discourse.conf to specify default_server like so:

  ## fix default discourse.conf
  - replace:
      filename: "/etc/nginx/conf.d/discourse.conf"
      from: "listen 80;"
      to: "listen 80 default_server;"

If you don’t nominate a default_server then the first server { } block is assumed to be the default and this causes problems.

It would be ideal if the default discourse.conf could be updated to include default_server. The other alternative is to use the DISCOURSE_HOSTNAME env to populate the server value instead of using server _;.

6 Likes