在 nginx 服务器中创建子域

Subdomain creation in nginx server

我正在尝试 redirect/rewrite url 为子页面创建子域。例如:http://example.com/user will return url as http://user.example.com,但无法想出任何办法。 我的应用程序位于 ruby railsnginx 服务器上。有什么技巧可以做到这一点吗?

您可以在 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
}

希望对您有所帮助。

更新

你只需要重写你的 nginx 配置。

server {
  listen       80;
  server_name  example.com;
  rewrite \/home$ $scheme://home.example.com;
}

然后保存配置,使用重新加载nginx sudo service nginx reload 重新加载配置文件。

如果您仍然担心,请告诉我。

您可能最好查看 Nginx 上的 wildcard subdomain,并为用户提供 Rails 路由。

请记住,Nginx 无法连接到您的数据库。所以 Nginx conf 实际上只需要能够通过服务器将网络流量发送到您的 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) }

以下内容应处理子域重定向。

server {
    server_name example.com;

    location ~ ^/(?<user>[^/]+)/?$ {
        return 301 $scheme://$user.$server_name;
    }
}