1. 程式人生 > 實用技巧 >使用https代替http

使用https代替http

使用https代替http

1、http模式下nginx配置

upstream django {
	server 127.0.0.1:9090;
}
server {

    listen 80;
    server_name localhost;
    charset utf-8;
    access_log /root/xxx/logs/nginx_access.log;
	error_log /root/xxx/logs/nginx_error.log;
    client_max_body_size 80m;

    location / {
      include /etc/nginx/uwsgi_params;
      uwsgi_pass django;
    }
    location /static {
      alias /root/scanweb/collectstatic;
    }
    location /upload {
      alias /root/scanweb/files;
    }
  }

2、https模式下nginx配置

注意:需要防火牆開放443埠

新增內容:

ssl on;
ssl_certificate /root/CHSmpSrc/keycer/certificate.crt;       # 證書檔案存放路徑
ssl_certificate_key /root/CHSmpSrc/keycer/private.key;       # 祕鑰檔案存放路徑

完整示例:

upstream django {
        server 127.0.0.1:9090;
}
server {
        listen 443 ssl;
        ssl on;      #開啟ssl證書認證
        ssl_certificate /root/CHSmpSrc/keycer/certificate.crt;       # 證書檔案存放路徑
        ssl_certificate_key /root/CHSmpSrc/keycer/private.key;       # 祕鑰檔案存放路徑
 
        server_name localhost;
        charset utf-8;
        access_log /root/xxx/logs/nginx_access.log;
	    error_log /root/xxx/logs/nginx_error.log;
        client_max_body_size 80M;
        
        location /media {
            alias /root/CHSmpSrc/smpauthensrc/media;
        }
        location / {
            include /etc/nginx/uwsgi_params;
            uwsgi_pass django;
        }
}

3、使80埠的http請求永久地重定向至https(既開放80埠又開放443埠)

upstream django {
        server 127.0.0.1:9090;
}

server {
        listen    443 ssl;
        server_name localhost;
 
        access_log  /data/xxx/access.log;
        keepalive_timeout 60;
         
         ssl on;      #開啟ssl證書認證
        # 證書路徑,根據實際情況改寫
        ssl_certificate /root/CHSmpSrc/keycer/certificate.crt;       # 證書檔案存放路徑
        ssl_certificate_key /root/CHSmpSrc/keycer/private.key;       # 祕鑰檔案存放路徑
        ssl_session_cache    shared:SSL:1m;
        ssl_session_timeout  5m;
        # 禁止在header中出現伺服器版本,防止黑客利用版本漏洞攻擊
        server_tokens off;
        
         location / {
            include /etc/nginx/uwsgi_params;
            uwsgi_pass django;
        }
}

server {
    # nignx監聽80埠,並重定向到https
    listen 80;
    server_name localhost;
 
    # 把http的域名請求轉成https
    return 301 https://$host$request_uri; 
}