首页 > 解决方案 > https:// 域 .com 重定向到 https:// www

问题描述

我的 nginx 配置主要使用 https,从 http 到 https 的所有重定向都可以正常工作,除了从https://example.com需要重定向到https://www.example.com有人能告诉我哪里出错了吗?

我尝试在监听 443 for example.com 的服务器块中添加重定向以重定向到 www.example.com,但我遇到了同样的问题。

server {
    server_name www.example.com;
    index index.php index.html index.htm;
    root /var/www/qc/public;

    error_log  /var/www/qc/error.log debug;
    access_log /var/www/qc/access.log;

    location / {
        include /etc/nginx/mime.types;
        index index.php;
        try_files $uri $uri/ /index.php?$query_string;
    }

    location ~ \.php$ {
        include snippets/fastcgi-php.conf;
        fastcgi_pass unix:/run/php/php7.0-fpm.sock;
    }

    listen 443 ssl; # managed by Certbot

    location /phpmyadmin {
        root /usr/share/;
        index index.php index.html index.htm;
        location ~ ^/phpmyadmin/(.+\.php)$ {
            try_files $uri =404;
            fastcgi_pass unix:/var/run/php/php7.0-fpm.sock;
            include fastcgi_params;
            fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;

        }
        location ~* ^/phpmyadmin/(.+\.(jpg|jpeg|gif|css|png|js|ico|html|xml|txt$
            root /usr/share/;
        }
    }

    ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem; # m$
    ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem; #$
}
server {
    if ($host = example.com) {
        return 301 https://$host$request_uri;
    } # managed by Certbot

    server_name example.com;
    return 404; # managed by Certbot
    listen 443 ssl; # managed by Certbot
    ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem; # m$
    ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem; #$
    include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot
}

server {
    server_name www.example.com example.com;
    return 301 https://www.example.com$request_uri;
    listen 80;
    return 404; # managed by Certbot
}

我希望将网址https://example.com重定向到https://www.example.com

标签: apachenginxconfiguration

解决方案


在您的 example.com 括号中,您不需要“if ($host = example.com) {”,因为您已经通过设置“server_name example.com;”来分隔进入此括号的主机;. 同样,当您重定向到 https://$host$request_uri; ,您将重定向到 example.com,而不是 www.example.com,从而创建了无限循环的重定向。

啤酒花这有帮助,这是应该工作的 example.com 配置:

server {

 location / {

    return 301 https://www.example.com$request_uri;
  }

    server_name example.com;
    return 404; # managed by Certbot
    listen 443 ssl; # managed by Certbot
    ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem; # m$
    ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem; #$
    include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot
}

推荐阅读