Nginx Remove WWW And Respond To Both

前端 未结 6 1765
粉色の甜心
粉色の甜心 2020-12-29 21:53

I have the following nginx configuration fragment:

server {
   listen 80;

   server_name mydomain.io;

   root /srv/www/domains/mydomain.io;

   index index         


        
相关标签:
6条回答
  • 2020-12-29 22:13

    According to https://www.nginx.com/resources/wiki/start/topics/tutorials/config_pitfalls/#server-name-if, you should use:

    server {
      server_name www.example.com;
      return 301 $scheme://example.com$request_uri;
    }
    server {
      server_name example.com;
      # [...]
    }
    
    0 讨论(0)
  • 2020-12-29 22:27

    On the first question - simply add both domains:

    server_name mydomain.io www.mydomain.io;
    

    For the second, you'll need this simple redirect:

    server {
          listen 80;
    
          server_name www.mydomain.io mydomain.io;
    
          if ($host = 'www.mydomain.io' ) {
             rewrite  ^/(.*)$  http://mydomain.io/$1  permanent;
          }
    
    0 讨论(0)
  • 2020-12-29 22:30
    server {
        listen 80;
        server_name www.mydomain.io;
        return 301 https://$host$request_uri;
    }
    
    server {
        listen 80;
        server_name mydomain.io;
        ...
    }
    
    0 讨论(0)
  • 2020-12-29 22:33

    I believe it's better to add two seperate server blocks to avoid unnecessary checking by the if block. I also use the $scheme variable so that HTTPS requests will not be redirected to their insecure counterparts.

    server {
        listen 80;
    
        server_name www.mydomain.io;
    
        rewrite ^ $scheme://mydomain.io$uri permanent;
    }
    
    server {
        listen 80;
    
        server_name mydomain.io;
    
        # your normal server block definitions here
    }
    
    0 讨论(0)
  • 2020-12-29 22:39

    Another way to code it :

    if ($http_host ~* "^www\.(.+)$"){
        rewrite ^(.*)$ http://%1$request_uri redirect;
    }
    

    It works even with multiple domain names on the same code.

    0 讨论(0)
  • 2020-12-29 22:39

    For a generic approach, without having to mention any specific domain or protocol, I have used this quite successfully:

      # rewrite to remove www.
      if ( $host ~ ^www\.(.+)$ ) {
        set $without_www $1;
        rewrite ^ $scheme://$without_www$uri permanent;
      }
    

    This will redirect: https://www.api.example.com/person/123?q=45 to https://api.example.com/person/123?q=45

    0 讨论(0)
提交回复
热议问题