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

View File

@ -41,7 +41,7 @@ export default {
// Reload handlebars
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;
templateName = js.replace(".js", "").replace("/assets/", "");
return _.each(Ember.View.views, function(view) {

View File

@ -3,7 +3,7 @@
export default function highlightSyntax($elem) {
const selector = Discourse.SiteSettings.autohighlight_all_code ? 'pre code' : 'pre code[class]';
$(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);
});
});

View File

@ -1,6 +1,6 @@
export default function($elem) {
$("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);
// do not lightbox spoiled images
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 !== '') {
rootURL = rootURL.replace(/\/$/, '');
if (rootURL.length > 0 && url.indexOf(rootURL + "/") === 0){
rootURL = "";
}
}
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() {
var router = this;

View File

@ -88,7 +88,7 @@ class ApplicationController < ActionController::Base
if (request.format && request.format.json?) || request.xhr? || !request.get?
rescue_discourse_actions(:not_logged_in, 403, true)
else
redirect_to "/"
redirect_to path("/")
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
if SiteSetting.login_required?
if SiteSetting.enable_sso?
redirect_to '/session/sso'
redirect_to path('/session/sso')
else
redirect_to :login
end
@ -387,7 +387,7 @@ class ApplicationController < ActionController::Base
end
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?
end
@ -404,6 +404,10 @@ class ApplicationController < ActionController::Base
protected
def path(p)
"#{GlobalSetting.relative_url_root}#{p}"
end
def render_post_json(post, add_raw=true)
post_serializer = PostSerializer.new(post, scope: guardian, root: false)
post_serializer.add_raw = add_raw

View File

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

View File

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

View File

@ -19,13 +19,13 @@ class InvitesController < ApplicationController
topic = invite.topics.first
if topic.present?
redirect_to "#{Discourse.base_uri}#{topic.relative_url}"
redirect_to path("#{topic.relative_url}")
return
end
end
end
redirect_to "/"
redirect_to path("/")
end
def create
@ -40,7 +40,7 @@ class InvitesController < ApplicationController
guardian.ensure_can_send_multiple_invites!(current_user)
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
else
render json: failed_json, status: 422
@ -77,13 +77,13 @@ class InvitesController < ApplicationController
topic = invite.topics.first
if topic.present?
redirect_to "#{Discourse.base_uri}#{topic.relative_url}"
redirect_to path("#{topic.relative_url}")
return
end
end
end
redirect_to "/"
redirect_to path("/")
end
def destroy

View File

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

View File

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

View File

@ -58,7 +58,7 @@ class UserAvatarsController < ApplicationController
upload ||= user.uploaded_avatar if user.uploaded_avatar_id == version
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
original = Discourse.store.path_for(upload)
if Discourse.store.external? || File.exists?(original)

View File

@ -142,7 +142,7 @@ class UsersController < ApplicationController
def my_redirect
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
end
raise Discourse::NotFound.new

View File

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

View File

@ -13,7 +13,7 @@
</div>
<% unless current_user %>
<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>
<% end %>
</div>

View File

@ -1,6 +1,6 @@
<% @list.categories.each do |c| %>
<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">
<%- if c.displayable_topics.present? %>
<% c.displayable_topics.each do |t| %>

View File

@ -11,7 +11,7 @@
</div>
<% end %>
<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 class="span8 recent-topics">
<h2 class="recent-topics-title"><%= t 'page_not_found.recent_topics' %></h2>
@ -21,7 +21,7 @@
</div>
<% end %>
<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>

View File

@ -19,7 +19,7 @@
<%= SiteCustomization.custom_header(session[:preview_style]) %>
<%- end %>
<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>
<div id="main-outlet" class="container">
<%= yield %>

View File

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

View File

@ -20,7 +20,7 @@
<% else %>
<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 %>
</p>
<% else %>

View File

@ -12,7 +12,7 @@
<p><%= t 'activation.approval_required' %></p>
<% else %>
<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' %>
<% end %>
<%end%>

View File

@ -156,6 +156,10 @@ module Discourse
require 'auth'
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
# So open id logs somewhere sane
OpenID::Util.logger = Rails.logger

View File

@ -119,3 +119,8 @@ new_version_emails = true
connection_reaper_age = 30
# run reap check every 30 seconds
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!
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
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
if (etag = env['HTTP_IF_NONE_MATCH']) && is_asset
name = $'
name = env['REQUEST_PATH'][(root.length)..-1]
etag = etag.gsub "\"", ""
asset = Rails.application.assets.find_asset(name)
if asset && asset.digest == etag

View File

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