nginx如何整合https呢?
下文笔者讲述nginx整个https的方法分享,如下所示
nginx整个https的实现思路
1.准备密钥文件 2.修改nginx.conf配置文件 3.重新load nginx即可完成nginx整合https例
生成密钥文件
使用keytool生成PKCS12格式的密钥 然后通过openssl取出cert和key 具体命令如下: # 生成PKCS12格式的密钥文件 keytool -genkey -alias localhost -keyalg RSA -keysize 2048 -sigalg SHA256withRSA -storetype PKCS12 -keystore localhost.p12 -dname CN=localhost,OU=Test,O=pkslow,L=Guangzhou,C=CN -validity 731 -storepass changeit -keypass changeit # 导出pem(certificate) openssl pkcs12 -nokeys -in ./localhost.p12 -out localhost.pem # 导出key openssl pkcs12 -nocerts -nodes -in ./localhost.p12 -out localhost.key
配置nginx.conf
新建一个nginx.conf文件 或修改原nginx.conf文件 /usr/local/nginx/conf目录下
server { listen 443 ssl; server_name localhost; ssl_certificate /key-path/localhost.pem; ssl_certificate_key /key-path/localhost.key; ssl_session_timeout 5m; ssl_ciphers ECDHE-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; location / { proxy_set_header HOST $host; proxy_set_header X-Forwarded-Proto $scheme; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_pass http://127.0.0.1:8000/; } } 注意事项: ssl_certificate:配置的是cert文件 ssl_certificate_key:配置的是private key文件。 proxy_pass http://127.0.0.1:8000/: 这个作用是把请求反向代理到这个地址上。
开启http并重定向到https
开启http很简单 将listen 80;加到listen 443 ssl 或 新加一个server配置
server { listen 443 ssl; server_name localhost; ssl_certificate /key-path/localhost.pem; ssl_certificate_key /key-path/localhost.key; ssl_session_timeout 5m; ssl_ciphers ECDHE-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; location / { proxy_set_header HOST $host; proxy_set_header X-Forwarded-Proto $scheme; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_pass http://127.0.0.1:8000/; } } server { listen 80; server_name localhost; location / { proxy_set_header HOST $host; proxy_set_header X-Forwarded-Proto $scheme; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_pass http://127.0.0.1:8000/; } }
nginx重定向到https两种方式
方式1: return 301 server { listen 80; server_name localhost; return 301 https://127.0.0.1$request_uri; } 方式2: 使用rewrite如下 server { listen 80; server_name localhost; rewrite ^(.*)$ https://$host$1 permanent; }
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。