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

前端 未结 17 2351
予麋鹿
予麋鹿 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;
    }
    

提交回复
热议问题