Question

I created a Rails app and I would like when I put any link pointing to my website, the "www" to be removed.

For example when someone enters http://www.mydomain.com/users into the browser address, this to be changed into http://mydomain.com/users when the page loads up.

So if I was working with apache I could add this lines to .htaccess file:

RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^(.*)$ http://%1/$1 [R=301,L]

However I am working with nginx and unicorn (I am not sure if unicorn has something to do with this).

Do I place something like that in my nginx configuration?

Any resource / point to the right direction will be really helpful.

Was it helpful?

Solution

As @Ricoxor answered, you could use a rewrite to get the correct functionality; however, this is listed as an examplary pitfall in the Nginx Pitfalls documentation.

The correct way to do this would be to write multiple server directives as shown by the documentation:

server {
  server_name www.domain.com;
  return 301 $scheme://domain.com$request_uri;
}
server {
  server_name domain.com;
  [...]
}

The reason this is more 'correct' is described at the page linked:

There are actually three problems here. The first being if directives. That's what we care about now. Why is this bad? Did you read If is Evil? With if directives Nginx is forced to evaluate every request for all domains. Evaluating every request against if directives is extremely inefficient. Avoid using if directives and use two server directives as shown.

OTHER TIPS

Try that :

Apache :

Options +FollowSymlinks
RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} ^www\.yourDomain\.com$ [NC]
RewriteRule ^(.*)$ http://yourDomain.fr/$1 [QSA,R=301,L]

Nginx :

# nginx configuration

location / {
  if ($http_host ~* "^www\.yourDomain\.com$"){
    rewrite ^(.*)$ http://yourDomain.fr/$1 redirect;
  }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top