FEATURE: add clean support for running Discourse in a subfolder

To setup set DISCOURSE_RELATIVE_URL_ROOT to the folder you wish
This commit is contained in:
Sam 2015-03-09 11:45:36 +11:00
parent 4c4183228f
commit f5af4768eb
27 changed files with 81 additions and 34 deletions

View File

@ -5,6 +5,10 @@ window.Discourse = Ember.Application.createWithMixins(Discourse.Ajax, {
rootElement: '#main', rootElement: '#main',
_docTitle: document.title, _docTitle: document.title,
script: function(url) {
return $LAB.script(this.getURL(url));
},
getURL: function(url) { getURL: function(url) {
if (!url) { return url; } if (!url) { return url; }
@ -16,6 +20,12 @@ window.Discourse = Ember.Application.createWithMixins(Discourse.Ajax, {
u = u.substring(0, u.length-1); u = u.substring(0, u.length-1);
} }
if (url.indexOf(u) !== -1) return url; if (url.indexOf(u) !== -1) return url;
if(u.length > 0 && url[0] !== "/") {
// we got to root this
url = "/" + url;
}
return u + url; return u + url;
}, },

View File

@ -41,7 +41,7 @@ export default {
// Reload handlebars // Reload handlebars
var js = me.name.replace(".hbs", "").replace("app/assets/javascripts", "/assets"); var js = me.name.replace(".hbs", "").replace("app/assets/javascripts", "/assets");
$LAB.script(js + "?hash=" + me.hash).wait(function() { Discourse.script(js + "?hash=" + me.hash).wait(function() {
var templateName; var templateName;
templateName = js.replace(".js", "").replace("/assets/", ""); templateName = js.replace(".js", "").replace("/assets/", "");
return _.each(Ember.View.views, function(view) { return _.each(Ember.View.views, function(view) {

View File

@ -3,7 +3,7 @@
export default function highlightSyntax($elem) { export default function highlightSyntax($elem) {
const selector = Discourse.SiteSettings.autohighlight_all_code ? 'pre code' : 'pre code[class]'; const selector = Discourse.SiteSettings.autohighlight_all_code ? 'pre code' : 'pre code[class]';
$(selector, $elem).each(function(i, e) { $(selector, $elem).each(function(i, e) {
return $LAB.script("/javascripts/highlight.pack.js").wait(function() { return Discourse.script("/javascripts/highlight.pack.js").wait(function() {
return hljs.highlightBlock(e); return hljs.highlightBlock(e);
}); });
}); });

View File

@ -1,6 +1,6 @@
export default function($elem) { export default function($elem) {
$("a.lightbox", $elem).each(function(i, e) { $("a.lightbox", $elem).each(function(i, e) {
$LAB.script("/javascripts/jquery.magnific-popup-min.js").wait(function() { Discourse.script("/javascripts/jquery.magnific-popup-min.js").wait(function() {
var $e = $(e); var $e = $(e);
// do not lightbox spoiled images // do not lightbox spoiled images
if ($e.parents(".spoiler").length > 0 || $e.parents(".spoiled").length > 0) { return; } if ($e.parents(".spoiler").length > 0 || $e.parents(".spoiled").length > 0) { return; }

View File

@ -204,6 +204,10 @@ Ember.DiscourseLocation = Ember.Object.extend({
if (url !== '') { if (url !== '') {
rootURL = rootURL.replace(/\/$/, ''); rootURL = rootURL.replace(/\/$/, '');
if (rootURL.length > 0 && url.indexOf(rootURL + "/") === 0){
rootURL = "";
}
} }
return rootURL + url; return rootURL + url;

View File

@ -113,6 +113,12 @@ Discourse.Route.reopenClass({
} }
}); });
if (Discourse.BaseUri) {
Discourse.Router.reopen({
rootURL: Discourse.BaseUri + "/"
});
}
Discourse.Router.map(function() { Discourse.Router.map(function() {
var router = this; var router = this;

View File

@ -88,7 +88,7 @@ class ApplicationController < ActionController::Base
if (request.format && request.format.json?) || request.xhr? || !request.get? if (request.format && request.format.json?) || request.xhr? || !request.get?
rescue_discourse_actions(:not_logged_in, 403, true) rescue_discourse_actions(:not_logged_in, 403, true)
else else
redirect_to "/" redirect_to path("/")
end end
end end
@ -379,7 +379,7 @@ class ApplicationController < ActionController::Base
# redirect user to the SSO page if we need to log in AND SSO is enabled # redirect user to the SSO page if we need to log in AND SSO is enabled
if SiteSetting.login_required? if SiteSetting.login_required?
if SiteSetting.enable_sso? if SiteSetting.enable_sso?
redirect_to '/session/sso' redirect_to path('/session/sso')
else else
redirect_to :login redirect_to :login
end end
@ -387,7 +387,7 @@ class ApplicationController < ActionController::Base
end end
def block_if_readonly_mode def block_if_readonly_mode
return if request.fullpath.start_with?("/admin/backups") return if request.fullpath.start_with?(path "/admin/backups")
raise Discourse::ReadOnly.new if !request.get? && Discourse.readonly_mode? raise Discourse::ReadOnly.new if !request.get? && Discourse.readonly_mode?
end end
@ -404,6 +404,10 @@ class ApplicationController < ActionController::Base
protected protected
def path(p)
"#{GlobalSetting.relative_url_root}#{p}"
end
def render_post_json(post, add_raw=true) def render_post_json(post, add_raw=true)
post_serializer = PostSerializer.new(post, scope: guardian, root: false) post_serializer = PostSerializer.new(post, scope: guardian, root: false)
post_serializer.add_raw = add_raw post_serializer.add_raw = add_raw

View File

@ -7,7 +7,7 @@ class CategoriesController < ApplicationController
skip_before_filter :check_xhr, only: [:index, :redirect] skip_before_filter :check_xhr, only: [:index, :redirect]
def redirect def redirect
redirect_to "/c/#{params[:path]}" redirect_to path("/c/#{params[:path]}")
end end
def index def index

View File

@ -17,7 +17,7 @@ class ForumsController < ApplicationController
end end
def home_redirect def home_redirect
redirect_to '/' redirect_to path('/')
end end
end end

View File

@ -19,13 +19,13 @@ class InvitesController < ApplicationController
topic = invite.topics.first topic = invite.topics.first
if topic.present? if topic.present?
redirect_to "#{Discourse.base_uri}#{topic.relative_url}" redirect_to path("#{topic.relative_url}")
return return
end end
end end
end end
redirect_to "/" redirect_to path("/")
end end
def create def create
@ -40,7 +40,7 @@ class InvitesController < ApplicationController
guardian.ensure_can_send_multiple_invites!(current_user) guardian.ensure_can_send_multiple_invites!(current_user)
end end
if Invite.invite_by_email(params[:email], current_user, topic=nil, group_ids) if Invite.invite_by_email(params[:email], current_user, _topic=nil, group_ids)
render json: success_json render json: success_json
else else
render json: failed_json, status: 422 render json: failed_json, status: 422
@ -77,13 +77,13 @@ class InvitesController < ApplicationController
topic = invite.topics.first topic = invite.topics.first
if topic.present? if topic.present?
redirect_to "#{Discourse.base_uri}#{topic.relative_url}" redirect_to path("#{topic.relative_url}")
return return
end end
end end
end end
redirect_to "/" redirect_to path("/")
end end
def destroy def destroy

View File

@ -12,7 +12,7 @@ class SessionController < ApplicationController
def sso def sso
if SiteSetting.enable_sso if SiteSetting.enable_sso
redirect_to DiscourseSingleSignOn.generate_url(params[:return_path] || '/') redirect_to DiscourseSingleSignOn.generate_url(params[:return_path] || path('/'))
else else
render nothing: true, status: 404 render nothing: true, status: 404
end end
@ -32,7 +32,7 @@ class SessionController < ApplicationController
redirect_to sso.to_url(sso.return_sso_url) redirect_to sso.to_url(sso.return_sso_url)
else else
session[:sso_payload] = request.query_string session[:sso_payload] = request.query_string
redirect_to '/login' redirect_to path('/login')
end end
else else
render nothing: true, status: 404 render nothing: true, status: 404
@ -47,7 +47,7 @@ class SessionController < ApplicationController
raise "User #{params[:session_id]} not found" if user.blank? raise "User #{params[:session_id]} not found" if user.blank?
log_on_user(user) log_on_user(user)
redirect_to "/" redirect_to path("/")
end end
def sso_login def sso_login
@ -80,9 +80,9 @@ class SessionController < ApplicationController
if return_path !~ /^\/[^\/]/ if return_path !~ /^\/[^\/]/
begin begin
uri = URI(return_path) uri = URI(return_path)
return_path = "/" unless uri.host == Discourse.current_hostname return_path = path("/") unless uri.host == Discourse.current_hostname
rescue rescue
return_path = "/" return_path = path("/")
end end
end end

View File

@ -4,7 +4,7 @@ class StaticController < ApplicationController
skip_before_filter :verify_authenticity_token, only: [:enter] skip_before_filter :verify_authenticity_token, only: [:enter]
def show def show
return redirect_to('/') if current_user && params[:id] == 'login' return redirect_to(path '/') if current_user && params[:id] == 'login'
map = { map = {
"faq" => {redirect: "faq_url", topic_id: "guidelines_topic_id"}, "faq" => {redirect: "faq_url", topic_id: "guidelines_topic_id"},
@ -60,15 +60,17 @@ class StaticController < ApplicationController
params.delete(:username) params.delete(:username)
params.delete(:password) params.delete(:password)
destination = "/" destination = path("/")
if params[:redirect].present? && !params[:redirect].match(login_path) if params[:redirect].present? && !params[:redirect].match(login_path)
begin begin
forum_uri = URI(Discourse.base_url) forum_uri = URI(Discourse.base_url)
uri = URI(params[:redirect]) uri = URI(params[:redirect])
if uri.path.present? && if uri.path.present? &&
(uri.host.blank? || uri.host == forum_uri.host) && (uri.host.blank? || uri.host == forum_uri.host) &&
uri.path !~ /\./ uri.path !~ /\./
destination = uri.path destination = uri.path
end end
rescue URI::InvalidURIError rescue URI::InvalidURIError

View File

@ -58,7 +58,7 @@ class UserAvatarsController < ApplicationController
upload ||= user.uploaded_avatar if user.uploaded_avatar_id == version upload ||= user.uploaded_avatar if user.uploaded_avatar_id == version
if user.uploaded_avatar && !upload if user.uploaded_avatar && !upload
return redirect_to "/user_avatar/#{hostname}/#{user.username_lower}/#{size}/#{user.uploaded_avatar_id}.png" return redirect_to path("/user_avatar/#{hostname}/#{user.username_lower}/#{size}/#{user.uploaded_avatar_id}.png")
elsif upload elsif upload
original = Discourse.store.path_for(upload) original = Discourse.store.path_for(upload)
if Discourse.store.external? || File.exists?(original) if Discourse.store.external? || File.exists?(original)

View File

@ -142,7 +142,7 @@ class UsersController < ApplicationController
def my_redirect def my_redirect
if current_user.present? && params[:path] =~ /^[a-z\-\/]+$/ if current_user.present? && params[:path] =~ /^[a-z\-\/]+$/
redirect_to "/users/#{current_user.username}/#{params[:path]}" redirect_to path("/users/#{current_user.username}/#{params[:path]}")
return return
end end
raise Discourse::NotFound.new raise Discourse::NotFound.new

View File

@ -23,6 +23,10 @@ module ApplicationHelper
end end
end end
def path(path)
"#{GlobalSetting.relative_url_root}#{path}"
end
def script(*args) def script(*args)
if SiteSetting.enable_cdn_js_debugging && GlobalSetting.cdn_url if SiteSetting.enable_cdn_js_debugging && GlobalSetting.cdn_url
tags = javascript_include_tag(*args, "crossorigin" => "anonymous") tags = javascript_include_tag(*args, "crossorigin" => "anonymous")

View File

@ -13,7 +13,7 @@
</div> </div>
<% unless current_user %> <% unless current_user %>
<div class='panel clearfix'> <div class='panel clearfix'>
<a href="/login" class='btn btn-primary btn-small'><i class="fa fa-user"></i><%= I18n.t('log_in') %></a> <a href="<%= path "/login"%>" class='btn btn-primary btn-small'><i class="fa fa-user"></i><%= I18n.t('log_in') %></a>
</div> </div>
<% end %> <% end %>
</div> </div>

View File

@ -1,6 +1,6 @@
<% @list.categories.each do |c| %> <% @list.categories.each do |c| %>
<div class="category"> <div class="category">
<h2><a href="/c/<%= c.slug.blank? ? c.id : c.slug %>"><%= c.name %></a></h2> <h2><a href="<%= path ("/c/" << (c.slug.blank? ? c.id : c.slug)) %>"><%= c.name %></a></h2>
<div class="topic-list"> <div class="topic-list">
<%- if c.displayable_topics.present? %> <%- if c.displayable_topics.present? %>
<% c.displayable_topics.each do |t| %> <% c.displayable_topics.each do |t| %>

View File

@ -11,7 +11,7 @@
</div> </div>
<% end %> <% end %>
<br/> <br/>
<a href="/latest" class="btn"><%= t 'page_not_found.see_more' %>&hellip;</a> <a href="<%= path "/latest" %>" class="btn"><%= t 'page_not_found.see_more' %>&hellip;</a>
</div> </div>
<div class="span8 recent-topics"> <div class="span8 recent-topics">
<h2 class="recent-topics-title"><%= t 'page_not_found.recent_topics' %></h2> <h2 class="recent-topics-title"><%= t 'page_not_found.recent_topics' %></h2>
@ -21,7 +21,7 @@
</div> </div>
<% end %> <% end %>
<br/> <br/>
<a href="/latest" class="btn"><%= t 'page_not_found.see_more' %>&hellip;</a> <a href="<%= path "/latest" %>" class="btn"><%= t 'page_not_found.see_more' %>&hellip;</a>
</div> </div>
</div> </div>

View File

@ -19,7 +19,7 @@
<%= SiteCustomization.custom_header(session[:preview_style]) %> <%= SiteCustomization.custom_header(session[:preview_style]) %>
<%- end %> <%- end %>
<header> <header>
<a href="/"><img src="<%=SiteSetting.logo_url%>" alt="<%=SiteSetting.title%>" id="site-logo"></a> <a href="<%= path "/" %>"><img src="<%=SiteSetting.logo_url%>" alt="<%=SiteSetting.title%>" id="site-logo"></a>
</header> </header>
<div id="main-outlet" class="container"> <div id="main-outlet" class="container">
<%= yield %> <%= yield %>

View File

@ -17,7 +17,7 @@
(function() { (function() {
function activateAccount() { function activateAccount() {
$('#activate-account-button').prop('disabled', true); $('#activate-account-button').prop('disabled', true);
$.ajax("/users/hp").then(function(hp) { $.ajax("<%= path "/users/hp" %>").then(function(hp) {
$('#password_confirmation').val(hp.value); $('#password_confirmation').val(hp.value);
$('#challenge').val(hp.challenge.split("").reverse().join("")); $('#challenge').val(hp.challenge.split("").reverse().join(""));
$('#activate-account-form').submit(); $('#activate-account-form').submit();

View File

@ -20,7 +20,7 @@
<% else %> <% else %>
<br> <br>
<br> <br>
<a class="btn" href="/"><%= t('password_reset.continue', site_name: SiteSetting.title) %></a> <a class="btn" href="<%= path "/" %>"><%= t('password_reset.continue', site_name: SiteSetting.title) %></a>
<% end %> <% end %>
</p> </p>
<% else %> <% else %>

View File

@ -12,7 +12,7 @@
<p><%= t 'activation.approval_required' %></p> <p><%= t 'activation.approval_required' %></p>
<% else %> <% else %>
<p><%= t('activation.please_continue') %></p> <p><%= t('activation.please_continue') %></p>
<p><a class="btn" href="/"><%= t('activation.continue_button', site_name: SiteSetting.title) -%></a></p> <p><a class="btn" href="<%= path "/" %>"><%= t('activation.continue_button', site_name: SiteSetting.title) -%></a></p>
<%= render partial: 'auto_redirect_home' %> <%= render partial: 'auto_redirect_home' %>
<% end %> <% end %>
<%end%> <%end%>

View File

@ -156,6 +156,10 @@ module Discourse
require 'auth' require 'auth'
Discourse.activate_plugins! unless Rails.env.test? and ENV['LOAD_PLUGINS'] != "1" Discourse.activate_plugins! unless Rails.env.test? and ENV['LOAD_PLUGINS'] != "1"
if GlobalSetting.relative_url_root.present?
config.relative_url_root = GlobalSetting.relative_url_root
end
config.after_initialize do config.after_initialize do
# So open id logs somewhere sane # So open id logs somewhere sane
OpenID::Util.logger = Rails.logger OpenID::Util.logger = Rails.logger

View File

@ -119,3 +119,8 @@ new_version_emails = true
connection_reaper_age = 30 connection_reaper_age = 30
# run reap check every 30 seconds # run reap check every 30 seconds
connection_reaper_interval = 30 connection_reaper_interval = 30
# set to relative URL (for subdirectory hosting)
# IMPORTANT: path must not include a trailing /
# EG: /forum
relative_url_root =

View File

@ -49,3 +49,6 @@ Logster.config.current_context = lambda{|env,&blk|
ActiveRecord::Base.connection_handler.clear_active_connections! ActiveRecord::Base.connection_handler.clear_active_connections!
end end
} }
# TODO logster should be able to do this automatically
Logster.config.subdirectory = "#{GlobalSetting.relative_url_root}/logs"

View File

@ -17,11 +17,12 @@ module Middleware
end end
def call(env) def call(env)
is_asset = (env['REQUEST_PATH'] =~ /^\/assets\//) root = "#{GlobalSetting.relative_url_root}/assets/"
is_asset = env['REQUEST_PATH'] && env['REQUEST_PATH'].starts_with?(root)
# hack to bypass all middleware if serving assets, a lot faster 4.5 seconds -> 1.5 seconds # hack to bypass all middleware if serving assets, a lot faster 4.5 seconds -> 1.5 seconds
if (etag = env['HTTP_IF_NONE_MATCH']) && is_asset if (etag = env['HTTP_IF_NONE_MATCH']) && is_asset
name = $' name = env['REQUEST_PATH'][(root.length)..-1]
etag = etag.gsub "\"", "" etag = etag.gsub "\"", ""
asset = Rails.application.assets.find_asset(name) asset = Rails.application.assets.find_asset(name)
if asset && asset.digest == etag if asset && asset.digest == etag

View File

@ -114,12 +114,16 @@ class DiscourseStylesheets
"#{GlobalSetting.cdn_url}#{stylesheet_relpath}?__ws=#{Discourse.current_hostname}" "#{GlobalSetting.cdn_url}#{stylesheet_relpath}?__ws=#{Discourse.current_hostname}"
end end
def root_path
"#{GlobalSetting.relative_url_root}/"
end
def stylesheet_relpath def stylesheet_relpath
"/#{CACHE_PATH}/#{stylesheet_filename}" "#{root_path}#{CACHE_PATH}/#{stylesheet_filename}"
end end
def stylesheet_relpath_no_digest def stylesheet_relpath_no_digest
"/#{CACHE_PATH}/#{stylesheet_filename_no_digest}" "#{root_path}#{CACHE_PATH}/#{stylesheet_filename_no_digest}"
end end
def stylesheet_filename def stylesheet_filename