nginx将www重定向到非www

时间:2019-10-20 18:44:29

标签: node.js nginx

我在服务器上配置了Nginx,但是我遇到了网址问题 如果直接使用example.com访问我的域,则可以正常运行(不安全-我必须重定向到https)

如果我尝试使用www.example.com直接访问它,它将无法正常工作,并且我收到了此消息

所以我主要有两个问题: 将非http重定向到https 并将www重定向到非www

我的运行nodejs应用程序的服务器

  

无法访问此站点www.example.com的服务器IP地址无法访问   找到了。 DNS_PROBE_FINISHED_NXDOMAIN

server {
    listen               80;
    listen               443 ssl;
    server_name          www.example.com;
    ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem; # managed by Certbot
    ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem; # managed by Certbot

    return 301 $scheme://example.com$request_uri;
}

server {
    listen  80;
    server_name example.com;
    location / {
    proxy_pass http://127.0.0.1:8080;
    proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
        proxy_redirect off;
     }

    location /api {
      proxy_pass http://127.0.0.1:3000;
      proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
        proxy_redirect off;
    }


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

1 个答案:

答案 0 :(得分:0)

要重定向到https,您应该有一个包含所有配置和listen 443 ssl;的服务器块,以及另一个具有以下配置的服务器块:

server {
    return 301 https://$host$request_uri;
    server_name example.com
    listen 80;
}

www站点是另一个域,您应该在dns服务器中为其设置IP地址。  您对www网站的配置看起来不错