diff --git a/README.md b/README.md index 44e11606..b4f880ac 100644 --- a/README.md +++ b/README.md @@ -32,6 +32,23 @@ This allows you to specify a different asset root for the directory of your appl By default this is set to `public_html/` +#### Canonical Host +This allows you to perform 301 redirects to a specific hostname, which can be useful for redirecting www to non-www (or vice versa). + +```json +{ + "canonical_host": "www.example.com" +} +``` + +You can use environment variables as well: + +```json +{ + "canonical_host": "${HOST}" +} +``` + #### Default Character Set This allows you to specify a character set for your text assets (HTML, Javascript, CSS, and so on). For most apps, this should be the default value of "UTF-8", but you can override it by setting `encoding`: diff --git a/scripts/config/lib/nginx_config.rb b/scripts/config/lib/nginx_config.rb index d4508471..6b93f258 100644 --- a/scripts/config/lib/nginx_config.rb +++ b/scripts/config/lib/nginx_config.rb @@ -6,6 +6,7 @@ class NginxConfig DEFAULT = { root: "public_html/", encoding: "UTF-8", + canonical_host: false, clean_urls: false, https_only: false, basic_auth: false, @@ -26,6 +27,9 @@ def initialize(json_file) json["root"] ||= DEFAULT[:root] json["encoding"] ||= DEFAULT[:encoding] + json["canonical_host"] ||= DEFAULT[:canonical_host] + json["canonical_host"] = NginxConfigUtil.interpolate(json["canonical_host"], ENV) if json["canonical_host"] + index = 0 json["proxies"] ||= {} json["proxies"].each do |loc, hash| diff --git a/scripts/config/templates/nginx.conf.erb b/scripts/config/templates/nginx.conf.erb index 930a335c..f128862b 100644 --- a/scripts/config/templates/nginx.conf.erb +++ b/scripts/config/templates/nginx.conf.erb @@ -77,6 +77,12 @@ http { } <% end %> + <% if canonical_host %> + if ($host != <%= canonical_host %>) { + return 301 $http_x_forwarded_proto://<%= canonical_host %>$request_uri; + } + <% end %> + <% routes.each do |route, path| %> location ~ ^<%= route %>$ { set $route <%= route %>;