简体   繁体   中英

Can't redirect https://www.example.com to https://example.com

I am using Nginx on Ubuntu and am able to redirect www.example.com to https://example.com but not from SSL to SSL with the www subdomain.

Here is my /etc/nginx/sites-enabled/myapp.conf :

# redirect non https traffic for the correct domains
server {
    if ($host = example.com) {
        return 301 https://$host$request_uri;
    } # managed by Certbot


    listen 80 default_server;
    listen [::]:80 default_server;

    server_name www.example.com;
    return 301 https://example.com$request_uri;
    return 404; # managed by Certbot

}

server {
    listen [::]:443 ssl ipv6only=on;
    listen 443 ssl;
    ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
    include /etc/letsencrypt/options-ssl-nginx.conf;
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem;

    # server for these domains
    server_name example.com;

    # first try to serve the erb version.
    index index.html;

    # Tell Nginx and Passenger where your app's 'public' directory is
    root /var/www/myapp/code/public;

    # Turn on Passenger
    passenger_enabled on;
    passenger_ruby /usr/local/rvm/gems/ruby-2.5.1/wrappers/ruby;
}

Is there any way to redirect all www subdomain traffic to root domain, even when entering the www URL after https://?

Thank you, any help is appreciated.

Yes, add the following server block:

# remove 'www'
server {
    listen 80;
    listen 443 ssl;
    server_name www.domain.com;
    return 301 https://example.com$request_uri;
}

This is from the nginx docs .

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