简体   繁体   中英

nginx redirect www to non-www

i have nginx config on my server, but i'm facing an issue with the url if access my domain directly using example.com it works (not secure - i have to redirect to https)

also if i tried to access it directly using www.example.com, it won't work and i got this message

so mainly i have two issues: redirect non-http to https and redirect www to non-www

my server running nodejs app

This site can't be reached www.example.com's server IP address could not be found. 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
}

To redirect to https, you should have a server block with all your config and listen 443 ssl; in it, and another server block with config like this one:

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

The www site is a different domain, you should set the ip address to it in your dns server. Your config for the www site looks ok

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM