码上风云

记录精彩的程序人生

  menu
24 文章
0 浏览
0 当前访客
ღゝ◡╹)ノ❤️

Nginx重定向http,https带www的和不带www的配置方法

网站开启 了 https,为了实现 http://zglgo.com,http://www.zglgo.comhttsp://zglgo.com 跳转到 httsp://www.zglgo.com,折腾了个把小时终于完成,现在把配置贴上,以作记录。

1.首先是 http://zglgo.com,http://www.zglgo.com 301 到 httsp://www.zglgo.com
在server里添加:
return 301 https://www.zglgo.com$request_uri;
完整配置如下

server {
        listen       80;
	server_name  zglgo.com www.zglgo.com;
	return 301 https://www.zglgo.com$request_uri;		
        #charset koi8-r;
        #access_log  logs/host.access.log  main;        	
        #error_page  404              /404.html;
        # redirect server error pages to the static page /50x.html
        #
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   /usr/local/nginx/html;
        }

    }

2.httsp://zglgo.com 301到httsp://www.zglgo.com
新建一个server,如下:

server{
	listen       443 ssl;
	server_name  zglgo.com;
	ssl_certificate      cert/zglgo.com.pem;
        ssl_certificate_key  cert/zglgo.com.key;
	return 301 https://www.zglgo.com$request_uri;
	}

3.应对 https 的请求,挂载 https 证书

# HTTPS server
    #
    server {
        listen       443 ssl;
	server_name   www.zglgo.com;
        ssl_certificate      cert/3600644_zglgo.com.pem;
        ssl_certificate_key  cert/3600644_zglgo.com.key;

        ssl_session_cache    shared:SSL:1m;
        ssl_session_timeout  5m;

        ssl_ciphers  HECDHE-RSA-AES128-GCM-SHA256:ECDHE:ECDH:AES:HIGH:!NULL:!aNULL:!MD5:!ADH:!RC4;
	#ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
        ssl_prefer_server_ciphers  on;
		
	#重要http转https跨域问题
	add_header Content-Security-Policy upgrade-insecure-requests;
		
        location / {
            proxy_pass   http://localhost:8080/;
	    proxy_set_header Host $http_host;
	    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
	    proxy_set_header X-Real-IP $remote_addr;
	    proxy_set_header X-Forwarded-Proto https;
            client_max_body_size 128m;			
        }
    }

4.重启nginx。


think twice, code once