Rails url_helper 踩坑,url 里指定 host 自动加了本地端口

tinyfeng · March 26, 2018 · Last by tinyfeng replied at March 27, 2018 · 2796 hits

这是我在 routes 里定义的一个路由:

get 'hello', to: 'hello#hello'

在 rails console 下进行如下操作:

Rails.application.routes.url_helpers.hello_hello_url host: 'http://abc.xyz'
=> "http://abc.xyz/hello"

而我在本地启动一个 server,rails s -p 3333

在 controller 里用了这个东西: hello_hello_url host: 'http://abc.xyz'

返回值是"http://abc.xyz:3333/hello",里面居然自己加了本地端口!

有没有方法能够把自动加的 3333 端口给禁掉

我知道手动添加 port 可以一定程度上解决这个问题:

hello_hello_url host: 'http://abc.xyz', port: 80 # => "http://abc.xyz/hello"

可是这时候以 https 来访问,显然会出错

这不是坑吧,又不是外链,不用加 host。

Reply to adamshen

在一些情况下需要手动指定 host,正常情况谁会那么折腾。。。

当然我也知道字符串拼接能实现我想要的 url,但是我想尝试使用 rails 自带的 method

Reply to tinyfeng

并不是 rails 非要给你加上端口号,而是 host、port、protocol 三个参数,如果你没有指定,就会使用你请求里的值作为默认值。你是用 3333 这个端口去请求页面的,所以默认的 port 值就是 3333,这个问题你部署以后就不存在了。https 也一样,你用 https 协议请求的,生成的 url 也是 https 的。一般来说,使用 url_helper 生成的链接都是内链,所以这种机制是 OK 的,并不是坑。

Reply to adamshen

你说的我同意,不过有时候在本地 dev 环境下的页面,引入一个 production 环境地址,通过这种方式生成,然后自动在 host 后加 3333 端口,导致 bug。。。

部署出去是 ok 的,这个没有争议。

Reply to tinyfeng

在本地 dev 环境下的页面,引入一个 production 环境地址

什么场景需要?

你怎么访问这个网址的,如果访问页面的时候就是带端口的,URL Helper 貌似会读请求头里的 Port 信息来构造 URL

7 Floor has deleted
Reply to jasl

通过 nginx,域名映射到 localhost:3333

Reply to adamshen

某些情况下,内网地址不可用,需要引用外网的地址,你懂的~

nginx 配置加上这个 proxy_set_header Host $http_host; 即可以了

Reply to moioo

location 里加上,好了,完美解决问题,给你献上 666~

You need to Sign in before reply, if you don't have an account, please Sign up first.