Rails 5 + Devise部署Heroku遇401 Unauthorized错误求助
Hey there! Let's figure out why your Devise-powered Rails 5 app is returning a 401 Unauthorized instead of redirecting to the login page when accessing the root path on Heroku. Here are the most common fixes to check:
Check Devise's navigational formats configuration
This is the most likely culprit. Devise usesnavigational_formatsto decide which request formats should trigger a redirect to the login page instead of returning a 401. In production environments, the default config sometimes restricts this to JSON-only requests.Open
config/initializers/devise.rband look for the line starting withconfig.navigational_formats. Make sure it includes:htmlso HTML requests get the expected redirect behavior:config.navigational_formats = ['*/*', :html, :json]If you only need support for HTML and JSON, you can also set it to
[:html, :json]. After updating, commit the change and redeploy to Heroku.Verify your controller's authentication hook
Double-check that yourHomeControllerhas the correct authentication setup. It should look like this:class HomeController < ApplicationController before_action :authenticate_user! def index # Your index action logic here end endIf you've overridden the
authenticate_user!method anywhere in your app, ensure it's following Devise's default behavior—like redirecting tonew_user_session_pathinstead of returning a 401 directly.Confirm production environment settings
Inconfig/environments/production.rb, verify these key settings:config.consider_all_requests_local = false(this is the default, but it's worth confirming)config.action_mailer.default_url_optionsis set to your Heroku app's URL, e.g.:config.action_mailer.default_url_options = { host: 'your-app-name.herokuapp.com' }
While this primarily affects password reset emails, it can occasionally impact Devise's routing logic for redirects.
Check for custom Devise controller overrides
If you've customized any Devise controllers (likeSessionsController), make sure you haven't modified the default redirect behavior for unauthenticated requests. Devise's out-of-the-box logic should automatically redirect unauthenticated HTML requests to the login page.
After trying these steps, redeploy your app to Heroku and test the root path again. If the issue persists, run heroku logs --tail to view real-time logs and look for additional clues about why the redirect isn't triggering as expected.
内容的提问来源于stack exchange,提问作者ArunKolhapur

