Chris Keele
Chris Keele

Reputation: 3453

Unexpected behavior with resource_url on Nginx and Unicorn

I have a simple unicorn+nginx setup on cpanel, deployed with capistrano. The nginx.conf server block looks like this:

server {
  error_log /var/log/nginx/vhost-error_log warn;
  listen 123.456.789.0;
  server_name my.dev.site.com www.my.dev.site.com;
  access_log /usr/local/apache/domlogs/my.dev.site.com-bytes_log bytes_log;
  access_log /usr/local/apache/domlogs/my.dev.site.com combined;
  root /home/me/sites/dev/current/public;
  try_files $uri/index.html $uri @unicorn;
  location @unicorn {
    proxy_pass http://unicorn_dev_site;
  }
  error_page 500 502 503 504 /500.html;
}

Under this setup, any reference to a resource like User yields odd behavior with the url helpers.

<%= users_path %> becomes my.dev.site.com/users as expected.

<%= users_url %> becomes unicorn_dev_site/users.

What's causing this, and what are the differences between these two helper methods that prompts this behavior?

Upvotes: 2

Views: 218

Answers (1)

Xavier Holt
Xavier Holt

Reputation: 14619

It's your proxying. The *_path helpers generate strings of the form

/path

while the *_url helpers generate strings like

http(s)://h.o.s.t/path

So thanks to your proxy setup, by the time a request gets to Rails, it's been tweaked so that the host is listed as http://unicorn_dev_site, which Rails faithfully replicates in the URLs it generates.

That said, there's usually no need to use *_url helpers instead of *_path helpers unless you have multiple hosts. If you want to use them, though, you have a couple options: You can set the default host in your controllers, and you can also set it on a per-URL basis with the :host option to url_for (I expect you can extend this pretty easily to the *_url helpers, but I don't know that for sure).

Anyway - hope that helps!

Upvotes: 3

Related Questions