Nginx no-www to www and www to no-www

前端 未结 17 2197
予麋鹿
予麋鹿 2020-11-22 09:53

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

相关标签:
17条回答
  • 2020-11-22 09:53

    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;
    }
    
    0 讨论(0)
  • 2020-11-22 09:53

    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
    
    0 讨论(0)
  • 2020-11-22 09:56

    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;
    }
    
    0 讨论(0)
  • 2020-11-22 10:01

    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;
    
    0 讨论(0)
  • 2020-11-22 10:02

    Unique format:

    server {
      listen 80;
      server_name "~^www\.(.*)$" ;
      return 301 https://$1$request_uri ;
    }
    
    0 讨论(0)
  • 2020-11-22 10:03

    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

    0 讨论(0)
提交回复
热议问题