Nginx 配置 HTTPS(多域名)

Nginx 配置

  首先, 需要把 http 都转发到 https, 需要使用 rewrite, 这样, 当访问 http://example.cn 会自动转发到 https://example.cn

server {
   	listen 80; # redirect to 443
    	server_name AAA.example.cn www.AAA.example.cn;
    	rewrite ^(.*)$  https://$host$1 permanent; 
}

   server {
           listen 80; # redirect to 443
           server_name BBB.example.cn www.BBB.example.cn;
           rewrite ^(.*)$  https://$host$1 permanent;
   }

然后就是真正的 https 部分了, 虽然域名不同, 但都监听 443 端口, 但有着不同的 server_name, 这样当收到请求时就可以根据请求的 server_name 不同来转发到不同的服务.

而服务自身像往常一样只要继续监听 80908091 即可.

server {
           	listen 443 ssl;
           	server_name AAA.example.cn www.AAA.example.cn;    

           	ssl_certificate "/home/yushan/demontf/2076603_AAA.example.cn.pem";   
           	ssl_certificate_key "/home/yushan/demontf/2076603_AAA.example.cn.key";    
           
           	location / {
               			proxy_pass http://127.0.0.1:8090;
               			proxy_set_header X-Real-IP $remote_addr;
               			proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
               			proxy_set_header Host $http_host;
               			proxy_set_header X-NginX-Proxy true;
               			proxy_redirect default;
	}
}


server {
   		listen 443 ssl; # redirect to https
   		server_name BBB.example.cn www.BBB.example.cn;
   		
   		ssl_certificate "/home/yushan/demontf/2005538_BBB.example.cn.pem";
   		ssl_certificate_key "/home/yushan/demontf/2005538_BBB.example.cn.key";
   		
   		location / {
   		              proxy_pass http://127.0.0.1:8091;
   		              proxy_set_header X-Real-IP $remote_addr;
   		              proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
   		              proxy_set_header Host $http_host;
   		              proxy_set_header X-NginX-Proxy true;
   		              proxy_redirect default;
   		}
}

配置修改好之后, 需要重启 Nginx.