FIX: Respect permalinks starting with "/category" (#7171)

FIX: Respect permalinks starting with “/category” (#7171)

diff --git a/app/controllers/application_controller.rb b/app/controllers/application_controller.rb
index 1f1de47..007288e 100644
--- a/app/controllers/application_controller.rb
+++ b/app/controllers/application_controller.rb
@@ -499,6 +499,13 @@ class ApplicationController < ActionController::Base
     SecureSession.new(session["secure_session_id"] ||= SecureRandom.hex)
   end
 
+  def handle_permalink(path)
+    permalink = Permalink.find_by_url(path)
+    if permalink && permalink.target_url
+      redirect_to permalink.target_url, status: :moved_permanently
+    end
+  end
+
   private
 
   def check_readonly_mode
diff --git a/app/controllers/categories_controller.rb b/app/controllers/categories_controller.rb
index 53236f4..3b9195c 100644
--- a/app/controllers/categories_controller.rb
+++ b/app/controllers/categories_controller.rb
@@ -9,6 +9,7 @@ class CategoriesController < ApplicationController
   skip_before_action :check_xhr, only: [:index, :categories_and_latest, :categories_and_top, :redirect]
 
   def redirect
+    return if handle_permalink("/category/#{params[:path]}")
     redirect_to path("/c/#{params[:path]}")
   end
 
diff --git a/spec/requests/categories_controller_spec.rb b/spec/requests/categories_controller_spec.rb
index 6bfca76..821e557 100644
--- a/spec/requests/categories_controller_spec.rb
+++ b/spec/requests/categories_controller_spec.rb
@@ -49,6 +49,20 @@ describe CategoriesController do
 
       expect(response.body).to have_tag "title", text: "Discourse - Official community"
     end
+
+    it "redirects /category paths to /c paths" do
+      get "/category/uncategorized"
+      expect(response.status).to eq(302)
+      expect(response.body).to include("c/uncategorized")
+    end
+
+    it "respects permalinks before redirecting /category paths to /c paths" do
+      perm = Permalink.create!(url: "category/something", category_id: category.id)
+
+      get "/category/something"
+      expect(response.status).to eq(301)
+      expect(response.body).to include(category.slug)
+    end
   end
 
   context 'extensibility event' do

GitHub sha: 2506acae

2 Likes