Created
March 10, 2021 03:21
-
-
Save xiaoysh8/1970feabef6b8cf51cab4cc6cbe9d3b8 to your computer and use it in GitHub Desktop.
开发环境Nginx配置SSL证书启用HTTPS
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 开发环境Nginx配置SSL证书启用HTTPS | |
| 作为一名前端开发者,在项目的开发过程中,可能需要将线上的静态资源直接指向本地。我一般习惯使用Nginx虚拟目录+修改Host的方式来完成。 | |
| 开发环境参数: | |
| 操作系统 : Ubuntu 16.04 LTS | |
| Nginx版本: nginx/1.12.2 | |
| 基于Nginx虚拟目录拦截HTTP请求 | |
| 假如线上静态资源的地址为: | |
| //static.example.com/my-project/bundle.min.js | |
| 开发环境本地静态资源路径为: | |
| /home/lvcy/my-project/dist/bundle.min.js | |
| 首选我们需要修改host将域名http://static.example.com指向本地 | |
| 127.0.0.1 static.example.com | |
| 然后通过alias来配置Nginx设置静态资源的虚拟目录,Nginx的配置如下所示: | |
| server { | |
| listen 80; | |
| server_name localhost; | |
| location /my-project/ { | |
| alias /home/lvcy/my-project/dist/; | |
| } | |
| } | |
| 通过上面简单的配置,就能够完美的将线上静态资源指向本地的开发环境目录,以便于开发过程中代码的调试。 | |
| 配置SSL使得Nginx支持HTTPS协议(开发环境) | |
| 很多情况下,项目的前端页面可能已经上线(已发布),并且通过HTTPS协议来访问页面(一般情况下公司不会在项目中混合使用HTTP和HTTPS协议,即当页面是基于HTTPS协议进行请求的,那么对应页面中的静态资源也必须通过HTTPS协议来请求)。此时前面的Nginx配置已经不能满足当前的代理需求(直接加HTTPS方式请求本地静态资源直接报404),因此我们需要让本地的Nginx也支持HTTPS协议。下面我们一步一步的来完成Nginx的SSL配置。 | |
| 一、生成私钥(server.key)及crt证书(server.crt) | |
| 首先需要创建一个目录来存放SSL证书相关文件 | |
| $ cd /etc/nginx | |
| $ sudo mkdir ssl | |
| $ cd ssl | |
| 1. 生成server.key | |
| $ openssl genrsa -des3 -out server.key 2048 | |
| 以上命令是基于des3算法生成的rsa私钥,在生成私钥时必须输入至少4位的密码。 | |
| 2. 生成无密码的server.key | |
| $ openssl rsa -in server.key -out server.key | |
| 3. 生成CA的crt | |
| $ openssl req -new -x509 -key server.key -out ca.crt -days 3650 | |
| 4. 基于ca.crt生成csr | |
| $ openssl req -new -key server.key -out server.csr | |
| 命令的执行过程中依次输入国家、省份、城市、公司、部门及邮箱等信息。 | |
| 5. 生成crt(已认证) | |
| $ openssl x509 -req -days 3650 -in server.csr -CA ca.crt -CAkey server.key -CAcreateserial -out server.crt | |
| 二、配置Nginx并支持HTTPS协议 | |
| 前面我们已经生成的用于支持HTTPS协议的SSL相关证书,接下来我们需要添加Nginx配置使得其能够真正支持HTTPS协议。 | |
| 支持HTTPS协议的Nginx配置如下所示: | |
| server { | |
| listen 80; | |
| server_name localhost; | |
| listen 443 ssl; | |
| ssl_certificate /etc/nginx/ssl/server.crt; | |
| ssl_certificate_key /etc/nginx/ssl/server.key; | |
| ssl_session_cache shared:SSL:1m; | |
| ssl_session_timeout 5m; | |
| ssl_protocols SSLv2 SSLv3 TLSv1.2; | |
| ssl_ciphers HIGH:!aNULL:!MD5; | |
| ssl_prefer_server_ciphers on; | |
| location /my-project/ { | |
| alias /home/lvcy/my-project/dist/; | |
| } | |
| } | |
| 重启nginx | |
| $ sudo nginx -s reload | |
| 至此,我们开发环境能够完美的支持HTTPS协议了。 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment