Nginx rewrite non-www-prefixed domain to www-prefixed domain

后端 未结 7 1123
旧时难觅i
旧时难觅i 2021-01-30 11:05

I see the Nginx HttpRewriteModule documentation has an example to rewrite a www-prefixed domain to a non-www-prefixed domain:

if ($host ~* www\\.(.*)) {
  set $h         


        
7条回答
  •  梦毁少年i
    2021-01-30 11:32

    Solution for multiple domains, working on nginx 1.17 for me:

    server {
            listen                                80;
            server_name                           .example.com;
    
            set $host_with_www                 $host;
    
            if ($host !~* www\.(.*)) {
                set $host_with_www www.$host;
            }
    
            return                                301 https://$host_with_www$request_uri;
    }
    

    In this config example additionally rewrites HTTP on HTTPS, if you don't want rewrite — replace https:// with http:// in return string.

    If you want keep protocol — use $scheme variable.

提交回复
热议问题