Getting 301 Redirect Error When Using Mailgun with Heroku Application

I’m having trouble with my Heroku app that uses Mailgun for email processing. Everything seems configured correctly but I keep getting errors.

The setup should work like this: when someone sends an email to my Mailgun address, it should automatically post the message to my app’s webhook endpoint. But instead of working properly, I see this error in my logs:

Will retry in 600 seconds: [email protected]http://my-app.herokuapp.com/webhook ‘subject line’ Moved Permanently Server response: 301 Moved Permanently

My Mailgun Configuration:

Filter: catch_all()
forward("http://my-app.herokuapp.com/webhook")

routes.rb:

post :webhook, to: 'emails#process'

emails_controller.rb:

class EmailsController < ApplicationController
  skip_before_action :verify_authenticity_token, only: [:process]

  def process
    puts "EMAIL WEBHOOK DATA: #{params}"
    
    # Process the email content here
    
    head 200
  end
end

What could be causing this 301 redirect issue? Any ideas would be helpful!

Had this exact problem last month and it drove me crazy for hours. The issue is definitely the HTTP vs HTTPS mismatch, but check one more thing - make sure your route definition includes the proper HTTP method constraint. In your routes.rb, try being more explicit:

post '/webhook', to: 'emails#process'

Also, Heroku apps sometimes have trailing slash issues with webhooks. After switching to HTTPS, if you’re still getting redirects, try adding a trailing slash to your webhook URL in Mailgun: https://my-app.herokuapp.com/webhook/. Some Rails configurations are picky about this depending on your routing setup.

The 301 redirect happens because Heroku automatically forces all HTTP requests to HTTPS for security. Your Mailgun setup is using http:// in the forwarding URL - that’s your problem right there. Just update your Mailgun forward URL to https://my-app.herokuapp.com/webhook. I ran into this exact same thing with my Heroku app. Kept seeing 301 redirects in the logs because Mailgun was posting to HTTP and getting bounced to HTTPS, which broke the webhooks.

yeah, it’s totally an http/https issue. also, double-check your app config for any redirects - lots of folks miss config.force_ssl = true, which can stack redirects on top of Heroku’s enforcement. try testing the webhook URL in your browser to ensure it’s actually reachable.