I am using nginx on Rackspace cloud following a tutorial and having searched the net and so far can\'t get this sorted.
I want www.mysite.com to go to mysite.com as
I combined the best of all the simple answers, without hard-coded domains.
301 permanent redirect from non-www to www (HTTP or HTTPS):
server {
if ($host !~ ^www\.) {
rewrite ^ $scheme://www.$host$request_uri permanent;
}
# Regular location configs...
}
If you prefer non-HTTPS, non-www to HTTPS, www redirect at the same time:
server {
listen 80;
if ($host !~ ^www\.) {
rewrite ^ https://www.$host$request_uri permanent;
}
rewrite ^ https://$host$request_uri permanent;
}
If you are having trouble getting this working, you may need to add the IP address of your server. For example:
server {
listen XXX.XXX.XXX.XXX:80;
listen XXX.XXX.XXX.XXX:443 ssl;
ssl_certificate /var/www/example.com/web/ssl/example.com.crt;
ssl_certificate_key /var/www/example.com/web/ssl/example.com.key;
server_name www.example.com;
return 301 $scheme://example.com$request_uri;
}
where XXX.XXX.XXX.XXX is the IP address (obviously).
Note: ssl crt and key location must be defined to properly redirect https requests
Don't forget to restart nginx after making the changes:
service nginx restart
You may find out you want to use the same config for more domains.
Following snippet removes www before any domain:
if ($host ~* ^www\.(.*)$) {
rewrite / $scheme://$1 permanent;
}
not sure if anyone notice it may be correct to return a 301 but browsers choke on it to doing
rewrite ^(.*)$ https://yoursite.com$1;
is faster than:
return 301 $scheme://yoursite.com$request_uri;
Unique format:
server {
listen 80;
server_name "~^www\.(.*)$" ;
return 301 https://$1$request_uri ;
}
If you don't want to hardcode the domain name, you can use this redirect block. The domain without the leading www is saved as variable $domain
which can be reused in the redirect statement.
server {
...
# Redirect www to non-www
if ( $host ~ ^www\.(?<domain>.+) ) {
rewrite ^/(.*)$ $scheme://$domain/$1;
}
}
REF: Redirecting a subdomain with a regular expression in nginx