Nginx no-www to www and www to no-www

前端 未结 17 2183
予麋鹿
予麋鹿 2020-11-22 09:53

I am using nginx on Rackspace cloud following a tutorial and having searched the net and so far can\'t get this sorted.

I want www.mysite.com to go to mysite.com as

17条回答
  •  抹茶落季
    2020-11-22 10:17

    You need two server blocks.

    Put these into your config file eg /etc/nginx/sites-available/sitename

    Let's say you decide to have http://example.com as the main address to use.

    Your config file should look like this:

    server {
            listen 80;
            listen [::]:80;
            server_name www.example.com;
            return 301 $scheme://example.com$request_uri;
    }
    server {
            listen 80;
            listen [::]:80;
            server_name example.com;
    
            # this is the main server block
            # insert ALL other config or settings in this server block
    }
    

    The first server block will hold the instructions to redirect any requests with the 'www' prefix. It listens to requests for the URL with 'www' prefix and redirects.

    It does nothing else.

    The second server block will hold your main address — the URL you want to use. All other settings go here like root, index, location, etc. Check the default file for these other settings you can include in the server block.

    The server needs two DNS A records.

    Name: @ IPAddress: your-ip-address (for the example.com URL)
    
    Name: www IPAddress: your-ip-address (for the www.example.com URL)
    

    For ipv6 create the pair of AAAA records using your-ipv6-address.

提交回复
热议问题