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

后端 未结 7 1217
旧时难觅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条回答
  •  死守一世寂寞
    2021-01-30 11:27

    Well I guess I don't really need the outer "if" statement since I'm only checking for domains of the form xxx.xxx anyways. The following works for me, though it's not robust. Let me know if there is a better solution.

        if ($host ~* ^([a-z0-9\-]+\.(com|net|org))$) {
            set $host_with_www www.$1;
            rewrite ^(.*)$ http://$host_with_www$1 permanent;
        }
    

    Edit: Added hyphen to the regular expression since it is a valid character in a hostname.

提交回复
热议问题