---
title: "单域名多Rails应用布置"
author: "gift5168xf"
date: "2009-10-08T20:35:00Z"
tags: []
slug: "rails"
draft: false
lastmod: "2009-10-14T01:49:41Z"
id: 487561
url: "https://sufery.iteye.com/blog/487561"
---

软件版本：ubuntu 8.04/lighttpd 1.4.19/ruby on rails 2.1.2

假定需要布置多 ror 应用的域名是 ror.example.com， 域名下一个子目录为一个应用，如 /app1, /app2..

首先，需要做的就是配置 lighty

```
$HTTP["host"] =~ "^ror\.example\.com$" {
 $HTTP["url"] =~ "^/app1" {
 alias.url = ("/app1" => "/path/to/app1/public")
 server.error-handler-404 = "/app1/dispatch.fcgi"
 fastcgi.server = ( ".fcgi" =>
 (( "socket" => "/tmp/app1.socket",
 "bin-path" => "/path/to/app1/public/dispatch.fcgi",
 "bin-environment" => ("RAILS_RELATIVE_URL_ROOT" => "/app1")
 )))
 }
}
```

关键就在于 **"bin-environment" =&gt; ("RAILS\_RELATIVE\_URL\_ROOT" =&gt; "/app1")** 这一行，告诉 rails 应用它所在的url。理论上，只要如此配置 lighty 就可以使用 rails 应用正常运行了， 因为根据 rails 的文档中关于 ActionController::AbstractRequest.relative\_url\_root 的描述：

> **relative\_url\_root** ()
> 
> Returns the path minus the web server relative installation directory. This can be set with the environment variable RAILS\_RELATIVE\_URL\_ROOT. It can be automatically extracted for Apache setups. If the server is not Apache, this method returns an empty string.
> 
> ```
>      # File vendor/rails/actionpack/lib/action_controller/request.rb, line 284


284:     def

 relative_url_root


285:       @@relative_url_root

 ||=

 case


286:         when

 @env

["RAILS_RELATIVE_URL_ROOT"

]
287:           @env

["RAILS_RELATIVE_URL_ROOT"

]
288:         when

 server_software

 ==

 'apache'


289:           @env

["SCRIPT_NAME"

].to_s

.sub

(/\/dispatch\.(fcgi|rb|cgi)$/

, ''

)
290:         else


291:           ''


292:       end


293:     end



> ```

根据上面所写，只要在 web server 中设置好 RAILS\_RELATIVE\_URL\_ROOT 环境变量，就可以使用 rails 正确运行，生成正确滴 url，可惜事实上如果只设定 lighty 的 RAILS\_RELATIVE\_URL\_ROOT 变量，是不能正常运行的。

经过试验，需要修改 rails app 的 config 目录下的 environment.rb 文件在最后添加上这一行：

```
ActionController::AbstractRequest.relative_url_root = ENV['RAILS_RELATIVE_URL_ROOT']
```

然后重启 lighty:

```
/etc/init.d/lighttpd restart
```

这样，rails 就能正常运转了