Nginx redirect Http to Https - what's wrong here?

后端 未结 2 693
既然无缘
既然无缘 2020-12-21 04:13

I have an Nginx server which should redirect all requests from http://www.domain.com and http://domain.com and https://domain.com to https://www.domain.com

So with o

相关标签:
2条回答
  • 2020-12-21 05:08

    The most nice way that I found looks like:

    server {
            listen 80;
            server_name example.com www.example.com;
            return 301 https://$server_name$request_uri;
    }
    
    server {
        listen       443 ssl;
        server_name  examle.com www.example.com;
    
        ssl_certificate /etc/nginx/conf.d/[crt];
        ssl_certificate_key /etc/nginx/conf.d/[key];
        ... 
    }
    

    In this way you can use $server_name instead of hardcoded values.

    0 讨论(0)
  • 2020-12-21 05:20

    So, I do this the reverse way. I literally had this issue the other day. One thing is the order was found to be important, and I really should have changed the "rewrite" rules to "return 301 ..." but I got lazy and didn't do that yet as I was in a bit of a hurry.

    Here is a snippet of my config

    #
    # Rewrite any http requests for domain.com to https.
    #
    server {
       listen       80;
       server_name domain.com;
       return 301 https://domain.com$request_uri;
    }
    #
    # Rewrite any http requests for www.domain.com to domain.com
    # using SSL
    #
    server {
       listen 80;
       server_name www.domain.com;
       rewrite ^/(.*) https://domain.com/$1 permanent;
    }
    
    #
    # The domain.com website
    #
    server {
       listen       443 ssl;
        server_name  domain.com;
    
        ssl_certificate /etc/nginx/conf.d/[crt];
        ssl_certificate_key /etc/nginx/conf.d/[key];
        ... Bunches of more stuff goes here. 
    }
    
    #
    # Rewrite any https requests for www.domain.com to domain.com
    # Note that this must be after the domain.com declaration.
    #
    server {
       listen 443;
       server_name www.domain.com;
       rewrite ^/(.*) https://domain.com/$1 permanent;
    }
    
    0 讨论(0)
提交回复
热议问题