首页 服务器应用

Nginx配置无www域名转向带www域名

2023-08-18 15:33 腾讯云开发者社区-腾讯云

打开 nginx.conf文件找到你的server配置段

这里,如果是单次重定向用 redirect, 如果永久跳转用 permanent,这里用 permanent

写法1

server{

    listen 80;

    server_name xxx.com www.xxx.com;

    index index.html index.php;

    root /data/www/wwwroot;

    if ($http_host !~ "^www.xxx.com$") {

        rewrite ^(.*) http://www.xxx.com$1 permanent;

    }

    ........................

}

写法2

server{

listen 80;

server_name www.test.com test.com;

if ($host != 'www.test.com' ) {

    rewrite ^/(.*)$ http://www.test.com/$1 permanent;

}

........

所有的非顶级域名都转过来

if ($host != 'XXX.com' ) {

    rewrite ^/(.*)$ http://XXX.com/$1 permanent;

}

【符号注释】

^ 匹配字符串的开始

/ 匹配域名的分隔符

. 匹配除换行符以外的任意字符

* 重复零次或更多次

(.*) 匹配任意字符

.* 匹配任意文本

$ 匹配字符串的结束

返回首页
返回顶部