在nginx服务器中创建子域名
我正在尝试重定向/重写url来为子页面创建子域名。例如:http://example.com/user将返回url作为http://user.example.com,但无法找出任何方法。 我的应用程序在红宝石在轨道上和nginx服务器。有没有这样做的伎俩?在nginx服务器中创建子域名
下应采取的子域重定向的照顾。
server {
server_name example.com;
location ~ ^/(?<user>[^/]+)/?$ {
return 301 $scheme://$user.$server_name;
}
}
嘿非常感谢。它效果很好。 多一个帮助,因为我是** ngnix服务器**的新手,你能否建议我一些在线资源来理解这些**重写**,**返回**和**正则表达式写入**概念清晰。 – tyson 2015-03-31 13:13:33
[nginx文档](http://nginx.org/en/docs/)是一个很好的起点。我还发现[nginx陷阱](http://wiki.nginx.org/Pitfalls)特别有用。 – 2015-03-31 16:43:18
你可以在你的Rails应用程序中做到这一点。一个简单的规则添加到你的路由文件:
get '/', to: 'users#show', constraints: { subdomain: /\d+/ }
然后什么都你访问*.example.com
,它会重定向到users#show
。
查看本教程以获取更多信息 Rails Routing Guide,第3.8部分。
否则,您可以在nginx配置中配置重写。我不确定它是否有效,请检查this guide
server {
listen 80;
server_name user.example.com;
return 301 example.com/user
}
希望它有帮助。
UPDATE
你只需要重写nginx的配置。
server {
listen 80;
server_name example.com;
rewrite \/home$ $scheme://home.example.com;
}
然后保存配置,使用 sudo service nginx reload
重新加载配置文件重新加载nginx的。
让我知道你是否仍然关注。
您可能会最好看的wildcard subdomain,并伴随着Rails
路由为用户。
请记住,Nginx没有连接到您的数据库。因此,Nginx
conf只需要能够通过服务器将Web流量发送到您的Rails应用程序。
如果用户存在,则可以使用Rails应用程序路由将您的流量发送到特定用户页面。你应该这样做有constraint
-
这里就是我想要做的:
/etc/nginx/nginx.conf (or wherever your nginx config is stored)
server {
server_name yourdomain.com *.yourdomain.com;
...
}
这会给你通过你的Rails应用程序传递任何子域请求的能力。
然后我会做你的Rails routes
:
config/routes.rb
#put this at the top of the file so it does not conflict
get '', to: 'users#index', constraints: lambda { |request| User.exists?(name: request.subdomain) }
截至目前如果有此配置/ routes.rb '根到:'网页#家' 得到'家' =>'pages#home'' 其中页面是我的目录存储在**/my_app/app/view/pages **和home是我的** home.html.erb **页面 – tyson 2015-03-31 09:41:00
您的问题是'我在尝试重定向/重写url为子页面创建子域名。“ - 我不明白”root“与那个有什么关系? – 2015-03-31 10:05:54
确定我的主线路由我到** home.html.erb **页面是'get'home'=>'pages#home'' – tyson 2015-03-31 10:32:08
你想如何处理一个请求来说:http://example.com/users/new? 你想要转到:http://new.example.com或http://users.example.com或其他东西? – Sahil 2015-03-31 11:33:06
我想'example.com/user'到'user.example.com' – tyson 2015-03-31 12:08:45