I am trying to redirect/rewrite url to create subdomain for subpages. eg: http://example.com/user will return url as http://user.example.com , but not able to figure out any way. My app is in ruby on rails and nginx server. Is there any trick to do this?
The following should take care of the subdomain redirection.
server {
server_name example.com;
location ~ ^/(?<user>[^/]+)/?$ {
return 301 $scheme://$user.$server_name;
}
}
You'll probably be best looking at a wildcard subdomain on Nginx
, and accompany that with Rails
routing for the users.
Remember, Nginx does not have connectivity to your database. So the Nginx
conf really just needs to be able to send web traffic through the server to your rails app.
The Rails app routing can then be used to send your traffic to specific user pages if the user exists. You'd do this with a constraint
--
Here's what I'd do:
/etc/nginx/nginx.conf (or wherever your nginx config is stored)
server {
server_name yourdomain.com *.yourdomain.com;
...
}
This will give you the ability to pass any subdomain requests through to your rails app.
I would then do this in your 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) }
You can do it in your Rails app. Simply add a rule to your routes files:
get '/', to: 'users#show', constraints: { subdomain: /\\d+/ }
Then what ever you visit *.example.com
, it will redirect to users#show
.
Check for this tutorial for more information Rails Routing Guide , Part 3.8.
Otherwise, you can config rewrite in nginx config. I am not sure it works, check this guide
server {
listen 80;
server_name user.example.com;
return 301 example.com/user
}
Hope it is helpful.
UPDATE
You just need to rewrite your nginx config.
server {
listen 80;
server_name example.com;
rewrite \/home$ $scheme://home.example.com;
}
Then save the config, reload nginx using sudo service nginx reload
to reload the config file.
Let me know if you still concern.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.