借鉴百度如何配置Nginx中http强制跳转https

  • 2019-01-29
  • 0
  • 0

传统是采用rewrite重定向或497 状态码跳转https

今天查看了下百度是如何实现

上面两种方法均会耗费服务器资源, 我们使用 curl 来看下百度是如何实现的 baidu.com 向 www.baidu.com 的跳转

通过index.html 刷新网页

$ curl baidu.com -vv 
* Rebuilt URL to: baidu.com/
*   Trying 220.181.57.217...
* TCP_NODELAY set
* Connected to baidu.com (220.181.57.217) port 80 (#0)
> GET / HTTP/1.1
> Host: baidu.com
> User-Agent: curl/7.51.0
> Accept: */*
> 
< HTTP/1.1 200 OK
< Date: Sat, 01 Apr 2017 06:32:35 GMT
< Server: Apache
< Last-Modified: Tue, 12 Jan 2010 13:48:00 GMT
< ETag: "51-47cf7e6ee8400"
< Accept-Ranges: bytes
< Content-Length: 81
< Cache-Control: max-age=86400
< Expires: Sun, 02 Apr 2017 06:32:35 GMT
< Connection: Keep-Alive
< Content-Type: text/html
< 
<html>
<meta http-equiv="refresh" content="0;url=http://www.baidu.com/">
</html>
* Curl_http_done: called premature == 0
* Connection #0 to host baidu.com left intact

可以看到百度很巧妙的利用meta的刷新作用,将baidu.com跳转到www.baidu.com
同理, 我们也可以用这个特性来实现http向https的跳转

# index.html
<html>  
    <meta http-equiv="refresh" content="0;url=https://chaidea.com/">
</html>

修改conf配置

server {
    listen 80;
    server_name chaidea.com;

    location / {
        # 将 index.html 文件放到下面的目录下
        root ./index.html;
    }
}
# 以下为正常配置,重点关注上面listent 80内容
server {
     listen 443 ssl;
     listen 80;
ssl                  on;
ssl_certificate   /etc/nginx/ssl/1789320_www.chaidea.com.pem;
ssl_certificate_key /etc/nginx/ssl/1789320_www.chaidea.com.key;
ssl_session_timeout 5m;
ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
ssl_ciphers AESGCM:ALL:!DH:!EXPORT:!RC4:+HIGH:!MEDIUM:!LOW:!aNULL:!eNULL;
ssl_prefer_server_ciphers on;
server_name  chaidea.com www.chaidea.com;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
     location / {
                proxy_pass http://127.0.0.1:xxxx/;
     }
}

以上,谢谢!

评论

还没有任何评论,你来说两句吧