简体   繁体   中英

How to redirect www.example.com to example.com in NginX?

When we open example.com (without HTTPS), the site loaded very well but when we open www.example.com (without HTTPS) it opens "Welcome of nginX" but I do not need this, we want to open example.com even if the URL is www.example.com .

NOTE: our site has "HTTPS" and when we open example.com , it will be redirected to https://example.com .

NOTE: when we open https://www.example.com , the site loaded well but when the URL is www.example.com or https://www.example.com it was not redirected.

We are using Ubuntu at AWS.

To do this I would recommend editing your nginx configuration file (usually in /etc/nginx/sites-enabled/you-example-config), adding return 301 as seen here , something like:

server {
    listen 80;
    listen 443;
    server_name www.example.com example.com;
    return 301 https://example.com$request_uri;
    #[...ssl settings go here, certs etc....]
}
server {
    listen 443;
    server_name example.com;
    # [...ssl and main settings go here...]
}

This will cause all requests to return https://example.com

Have you defined a separate server for each of the options? See example snippet below. Your question looks very similar to this question and this question which both have a lot more information that I won't copy paste here.

This link might also help creating-nginx-rewrite-rules

server {
    listen 80;
    listen 443 ssl;
    server_name www.example.com;
    return 301 $scheme://example.com$request_uri;
}

server {
    listen 80;
    server_name example.com;
    # here goes the rest of your config file
    # example 
    location / {

        rewrite ^/cp/login?$ /cp/login.php last;
        # etc etc...

    }

}

$scheme is the protocol (HTTP or HTTPS) and $request_uri is the full URI including arguments.

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